码迷,mamicode.com
首页 > 其他好文 > 详细

HUD5423 Rikka with Tree(DFS)

时间:2015-08-30 17:27:36      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

题目链接: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 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 A技术分享
and 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(1n1000)技术分享
.
Then n1技术分享
lines follow. Each line contains two numbers u,v(1u,vn)技术分享
, 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
此题满足条件的只有一种情况,即: 树从上到下的结点数依次为: 1, 1, 1, ,,,,x(x为任意). 也即是说,只有最后一层的结点数才能大于 1 .
dfs 求出每层的结点数, 就能判断出答案。
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
using namespace std;

bool ok;
vector<int> a[1010];
int num[1010];

void dfs(int u, int fa, int d)
{
    num[d]++;
    int len = a[u].size();
    for(int i=0; i<len; i++)
    {
        if(a[u][i]==fa) continue;
        dfs(a[u][i], u, d+1);
    }
}

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        for(int i=0; i<1010; i++)
        a[i].clear();
        memset(num, 0, sizeof(num));
        for(int i=1; i<n; i++)
        {
            int x, y;
            scanf("%d%d", &x, &y);
            a[x].push_back(y);
            a[y].push_back(x);
        }
        ok = false;
        dfs(1, -1, 1);
        for(int i=1; i<1010; i++)
        {
            if(num[i-1]>1&&num[i])
            ok = true;
        }
        if(ok) printf("NO\n");
        else printf("YES\n");
    }
    return 0;
}

 

 

HUD5423 Rikka with Tree(DFS)

标签:

原文地址:http://www.cnblogs.com/acm1314/p/4771156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!