Problem Description
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?
Input
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.
Output
For each testcase, if the tree is special print "YES" , otherwise print "NO".
Sample Input
3
1 2
2 3
4
1 2
2 3
1 4
Sample Output
YES
NO
Hint
For the second testcase, this tree is similiar with the given tree:
4
1 2
1 4
3 4
Source
根据题意可以构造出来的特殊树有三种情况(全是以结点1为根节点),,第一种是一条直线,第二种是一条直线末尾开花,第三种是直接开花。如图所示。然后就可以知道对于每一个深度的点数为1,1,1,...,x,0,0,...。然后dfs一遍找一下就可以了。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<vector> 5 #include<set> 6 #include<map> 7 #include<queue> 8 #include<algorithm> 9 using namespace std; 10 #define N 1006 11 vector<int>g[N]; 12 vector<int>deep[N]; 13 int vis[N]; 14 void dfs(int st,int d){ 15 vis[st]=1; 16 deep[d].push_back(st); 17 for(int i=0;i<g[st].size();i++){ 18 int u=g[st][i]; 19 if(!vis[u]){ 20 dfs(u,d+1); 21 } 22 } 23 } 24 int main() 25 { 26 int n; 27 while(scanf("%d",&n)==1){ 28 29 for(int i=0;i<=n;i++) { 30 g[i].clear(); 31 deep[i].clear(); 32 } 33 memset(vis,0,sizeof(vis)); 34 35 for(int i=1;i<n;i++){ 36 int u,v; 37 scanf("%d%d",&u,&v); 38 g[u].push_back(v); 39 g[v].push_back(u); 40 } 41 dfs(1,0); 42 43 44 int t=0; 45 while(deep[t].size()==1) t++; 46 47 int num=deep[t].size(); 48 if(num+t!=n) { 49 printf("NO "); 50 }else{ 51 printf("YES "); 52 } 53 54 } 55 return 0; 56 }