Rikka with Tree HDU

来源:互联网 发布:淘宝费列罗真假 编辑:程序博客网 时间:2024/05/18 01:32

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 TT, let F(T,i)F(T,i) be the distance between vertice 1 and vertice ii.(The length of each edge is 1). 

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

Two trees AA and BB are different if and only if they have different numbers of vertices or there exist an number ii which vertice ii have different fathers in tree AA and tree BB when vertice 1 is root. 

Tree AA is special if and only if there doesn't exist an tree BBwhich AA and BB are different and AA and BB 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(1n1000)n(1≤n≤1000).

Then n1n−1 lines follow. Each line contains two numbers u,v(1u,vn)u,v(1≤u,v≤n) , which means there is an edge between uu and vv.
Output
For each testcase, if the tree is special print "YES" , otherwise print "NO".
Sample Input
31 22 341 22 31 4
Sample Output
YESNO          
Hint
For the second testcase, this tree is similiar with the given tree:41 21 43 4

题解:这道题 最重要就是理解题意 什么样的树是特殊的 就是 一个点他如果有爷爷 那么他的爷爷的孩子只能有一个 

#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<queue>
#include<map>
#include<algorithm>
#include<vector>
using namespace std;
int pre[1100];
int main()
{
    int n;
    map<int,int>q;
    while(~scanf("%d",&n))
    {
     q.clear();
     for(int i=1;i<=n;i++)
        pre[i]=i;
     int a,b;
     for(int i=1;i<n;i++)
     {
         scanf("%d%d",&a,&b);
         pre[b]=a;
         q[a]++;
     }
     int flag=1;
     for(int i=1;i<=n;i++)
     {
         if(pre[pre[i]]!=pre[i]&&q[pre[pre[i]]]>1)
         {
             flag=0;
         }
     }
     if(flag)
        printf("YES\n");
     else
         printf("NO\n");
    }
}

0 0