HUD5423 Rikka with Tree(DFS)

时间:2022-03-30 12:27:18

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5423

Rikka with Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Total Submission(s): 321    Accepted Submission(s): 162

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 THUD5423  Rikka with Tree(DFS)
, let F(T,i)HUD5423  Rikka with Tree(DFS)
be the distance between vertice 1 and vertice iHUD5423  Rikka with Tree(DFS)
.(The length of each edge is 1).
Two trees AHUD5423  Rikka with Tree(DFS)
and BHUD5423  Rikka with Tree(DFS)
are similiar if and only if the have same number of vertices and for each iHUD5423  Rikka with Tree(DFS)
meet F(A,i)=F(B,i)HUD5423  Rikka with Tree(DFS)
.
Two trees AHUD5423  Rikka with Tree(DFS)
and BHUD5423  Rikka with Tree(DFS)
are different if and only if they have different numbers of vertices or there exist an number iHUD5423  Rikka with Tree(DFS)
which vertice iHUD5423  Rikka with Tree(DFS)
have different fathers in tree AHUD5423  Rikka with Tree(DFS)
and tree BHUD5423  Rikka with Tree(DFS)
when vertice 1 is root.
Tree AHUD5423  Rikka with Tree(DFS)
is special if and only if there doesn't exist an tree BHUD5423  Rikka with Tree(DFS)
which AHUD5423  Rikka with Tree(DFS)
and BHUD5423  Rikka with Tree(DFS)
are different and AHUD5423  Rikka with Tree(DFS)
and BHUD5423  Rikka with Tree(DFS)
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)HUD5423  Rikka with Tree(DFS)
.
Then n−1HUD5423  Rikka with Tree(DFS)
lines follow. Each line contains two numbers u,v(1≤u,v≤n)HUD5423  Rikka with Tree(DFS)
, which means there is an edge between uHUD5423  Rikka with Tree(DFS)
and vHUD5423  Rikka with Tree(DFS)
.
 
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
此题满足条件的只有一种情况,即: 树从上到下的结点数依次为: 1, 1, 1, ,,,,x(x为任意). 也即是说,只有最后一层的结点数才能大于 1 .
dfs 求出每层的结点数, 就能判断出答案。
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
using namespace std; bool ok;
vector<int> a[];
int num[]; void dfs(int u, int fa, int d)
{
num[d]++;
int len = a[u].size();
for(int i=; i<len; i++)
{
if(a[u][i]==fa) continue;
dfs(a[u][i], u, d+);
}
} int main()
{
int n;
while(~scanf("%d", &n))
{
for(int i=; i<; i++)
a[i].clear();
memset(num, , sizeof(num));
for(int i=; i<n; i++)
{
int x, y;
scanf("%d%d", &x, &y);
a[x].push_back(y);
a[y].push_back(x);
}
ok = false;
dfs(, -, );
for(int i=; i<; i++)
{
if(num[i-]>&&num[i])
ok = true;
}
if(ok) printf("NO\n");
else printf("YES\n");
}
return ;
}