POJ 1308 Is It A Tree?

题目链接:http://poj.org/problem?id=1703


方法一:方非并查集做法,需要为树就是说只有一个节点的入度为0,其余的节点入度为1


#include<cstdio>
#include<cstring>
#define N 15

int main ()
{
    int node[N];
    int vis[N];
    int a, b;
    int t = 1;
    while(scanf("%d %d", &a, &b) != EOF)
    {
        if(a == -1 && b == -1) break;

        if(a == 0 && b== 0){printf("Case %d is a tree.\n",t++);continue;}

        int flag = 0;
        if(a == b) flag = 1;

        memset(node, 0, sizeof(node));
        memset(vis, 0, sizeof(vis));

        vis[a] = 1; vis[b] = 1;
        node[b]++;
        while(1)
        {
            scanf("%d %d", &a, &b);
            if(a == 0 && b== 0) break;
            vis[a] = 1; vis[b] = 1;
            node[b]++;
        }

        int cnt = 0;
        for(int i = 1; i < N; i++){
            if(vis[i]!=0 && node[i] == 0)
                cnt++;
            if(vis[i]!=0 && node[i] > 1)
                flag = 1;
        }

        if(cnt != 1) flag = 1;

        if(!flag)
             printf("Case %d is a tree.\n", t++);
        else
            printf("Case %d is not a tree.\n", t++);
    }
    return 0;
}


你可能感兴趣的:(POJ 1308 Is It A Tree?)