CODEFORCES 430E Guess the Tree <dfs搜索建树>
2016-08-10 15:34
501 查看
传送门:http://codeforces.com/problemset/problem/430/E
题意:给你一棵树的所有节点子树节点总数,问这棵树是否存在,每个节点如果有子节点,那么必须保证有两个以上的的儿子
分析:dfs,递归
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[26];
int n;
bool vis[26];
bool dfs(int pre,int val,int child)
{
//printf("pre = %d val =%d child = %d\n",pre,val,child);
if(pre == n) return true;
if(val +1== a[pre])
{
if(child != 1&&dfs(pre+1,0,0)) return true;
return false;
}
int tot = 0;
for(int i=0; i<n; i++)
{
if(!vis[i]&&val+a[i]<a[pre]&&tot!=a[i])
{
//printf("i = %d\n",i);
tot = a[i];
vis[i] = true;
if(dfs(pre,val+a[i],child+1)) return true;
vis[i]=false;
}
}
return false;
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("in.txt","w",stdout);
#endif
cin >> n;
for(int i=0; i<n; i++) cin >> a[i];
sort(a,a+n);
memset(vis,false,sizeof(vis));
if(a[n-1] == n&&dfs(0,0,0)) puts("YES");
else
puts("NO");
return 0;
}
题意:给你一棵树的所有节点子树节点总数,问这棵树是否存在,每个节点如果有子节点,那么必须保证有两个以上的的儿子
分析:dfs,递归
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[26];
int n;
bool vis[26];
bool dfs(int pre,int val,int child)
{
//printf("pre = %d val =%d child = %d\n",pre,val,child);
if(pre == n) return true;
if(val +1== a[pre])
{
if(child != 1&&dfs(pre+1,0,0)) return true;
return false;
}
int tot = 0;
for(int i=0; i<n; i++)
{
if(!vis[i]&&val+a[i]<a[pre]&&tot!=a[i])
{
//printf("i = %d\n",i);
tot = a[i];
vis[i] = true;
if(dfs(pre,val+a[i],child+1)) return true;
vis[i]=false;
}
}
return false;
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("in.txt","w",stdout);
#endif
cin >> n;
for(int i=0; i<n; i++) cin >> a[i];
sort(a,a+n);
memset(vis,false,sizeof(vis));
if(a[n-1] == n&&dfs(0,0,0)) puts("YES");
else
puts("NO");
return 0;
}
相关文章推荐
- 基础理论部分
- request
- esay UI实现无限级tree
- android Gui系统之WMS(2)----窗口的添加
- Android FrameWork源码浅析之(一)--handler,looper,messagequeue
- HDU 1423 Greatest Common Increasing Subsequence(最长公共子序列+最长不下降子序列)
- iOS UI篇- 退出键盘
- ECSHOP安装百度编辑UEditor教程
- EventBus源码阅读(17)-EventBusBuilder
- iOS 单击图片UIImage提取图片上的颜色UIColor (OC)
- poj 1947 Rebuilding Roads(基础)
- 对chain.doFilter(request,response)的理解
- mysqldump: Got error: 1066: Not unique table/alias: 'dept' when using LOCK TABLES
- iOS - UIViewController
- 修改UITextField的placeHolder的颜色及字体大小
- 装机员U盘启动PE制作工具V4.0(UEFI+UD)
- 安卓 简单的 联系人快速检索控件QuickIndexBar实现
- mui下拉加载更多
- Kinect V2 多关节捕捉应用中break 与 continue的妙用
- postfix-3.1.1编译安装成功, 启动的时候警报:postfix: warning: smtputf8_enable is true, but EAI support is not compi