您的位置:首页 > 产品设计 > UI/UE

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: