您的位置:首页 > 其它

hdu 5423 Rikka with Tree(dfs)

2015-08-29 22:18 302 查看
[align=left]Problem Description[/align]

As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

For a tree T, let F(T,i) be the distance between vertice 1 and vertice i.(The length of each edge is 1).

Two trees A and B are similiar if and only if the have same number of vertices and for each i meet F(A,i)=F(B,i).

Two trees A and B are different if and only if they have different numbers of vertices or there exist an number i which vertice i have different fathers in tree Aand tree B when vertice 1 is root.

Tree A is special if and only if there doesn't exist an tree B which A and B are different and A and B are similiar.

Now he wants to know if a tree is special.

It is too difficult for Rikka. Can you help her?


[align=left]Input[/align]

There are no more than 100 testcases.

For each testcase, the first line contains a number n(1≤n≤1000).

Then n−1 lines follow. Each line contains two numbers u,v(1≤u,v≤n) , which means there is an edge between u and v.


[align=left]Output[/align]

For each testcase, if the tree is special print "YES" , otherwise print "NO".


[align=left]Sample Input[/align]

3
1 2
2 3
4
1 2
2 3
1 4


[align=left]Sample Output[/align]

YES
NO


Hint

For the second testcase, this tree is similiar with the given tree:

4

1 2

1 4

3 4

[align=left]Source[/align]
BestCoder Round #53 (div.2)

根据题意可以构造出来的特殊树有三种情况(全是以结点1为根节点),,第一种是一条直线,第二种是一条直线末尾开花,第三种是直接开花。如图所示。然后就可以知道对于每一个深度的点数为1,1,1,...,x,0,0,...。然后dfs一遍找一下就可以了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
#define N 1006
vector<int>g
;
vector<int>deep
;
int vis
;
void dfs(int st,int d){
vis[st]=1;
deep[d].push_back(st);
for(int i=0;i<g[st].size();i++){
int u=g[st][i];
if(!vis[u]){
dfs(u,d+1);
}
}
}
int main()
{
int n;
while(scanf("%d",&n)==1){

for(int i=0;i<=n;i++) {
g[i].clear();
deep[i].clear();
}
memset(vis,0,sizeof(vis));

for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1,0);

int t=0;
while(deep[t].size()==1) t++;

int num=deep[t].size();
if(num+t!=n) {
printf("NO\n");
}else{
printf("YES\n");
}

}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: