ACM学习历程—HDU5423 Rikka with Tree(搜索)

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
Hint
For the second testcase, this tree is similiar with the given tree:
4
1 2
1 4
3 4

题目要求的那个特殊的树其实就是一条直链,然后在链的末端接上若干节点,类似于扫帚的形状。

也就是最后一层的节点下方没有子节点,倒数第二层的节点下方可以有若干子节点,其余节点均只有一个子节点。

用dfs搜索每一层的节点进行判断即可。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
#include <queue>
#include <vector>
#define LL long long

using namespace std;

const int maxN = 1005;

struct Edge
{
    int to, next;
    //int val;
}edge[maxN*2];

int head[maxN], cnt;

void addEdge(int u, int v)
{
    edge[cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt;
    cnt++;
}

void initEdge()
{
    memset(head, -1, sizeof(head));
    cnt = 0;
}

int n;
bool vis[maxN];
int maxDepth;
bool flag;

bool input()
{
    if (scanf("%d", &n) == EOF)
        return false;
    initEdge();
    memset(vis, false, sizeof(vis));
    maxDepth = 0;
    flag = true;
    int u, v;
    for (int i = 1; i < n; ++i)
    {
        scanf("%d%d", &u, &v);
        addEdge(u, v);
        addEdge(v, u);
    }
    return true;
}

void dfs(int now, int depth)
{
    if (flag == false)
        return;
    int cnt = 0;
    vis[now] = true;
    for (int i = head[now]; i != -1; i = edge[i].next)
    {
        if (vis[edge[i].to])
            continue;
        dfs(edge[i].to, depth+1);
        cnt++;
    }
    if (cnt == 0)
        return;
    maxDepth = max(maxDepth, depth);
    if (depth != maxDepth && cnt != 1)
        flag = false;
}

void work()
{
    dfs(1, 0);
    if (flag)
        printf("YES
");
    else
        printf("NO
");
}

int main()
{
    //freopen("test.in", "r", stdin);
    while (input())
    {
        work();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/andyqsmart/p/4791165.html