标签:
我的解法就是去构造了一棵树
以数组的存储方式
数组的值存放节点的根!
排除空树
剩下的就是出现环和多根节点的情况
也就是排除森林和有一个节点多个入度的情况
排除森林就用到了并查集
也就是便利数组让其只有一个根
排除多个入度的情况更简单
就是把这个点插入到数上时
如果这个点已经有了根节点,就出现了两个入度
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int sett[1000 + 100],g[1000 + 100];
int find2(int x)
{
    while(x != sett[x] ) x = sett[x];
    return x;
}
int main()
{
    int x,y,flag=1,cases=1;
    while(scanf("%d%d",&x,&y)){
    flag=1;
        for(int i=1;i<=1000;i++) sett[i]=i;
//        for(int i=1;i<=1000;i++) g[i]=i;
        memset(g,0,sizeof(g));
        if(x == 0 && y == 0) flag=0;
        if(x < 0 && y < 0) break;
        else sett[y]=x;
        g[x]=1;
        g[y]=1;
        while(scanf("%d%d",&x,&y)){
        g[x]=1;
        g[y]=1;
            if(!x&&!y) break;
            int fx = sett[x];
            int fy = sett[y];
            if( fy != y) //out circle and two roots
                flag=0;
            else sett[fy]=fx;
        }
        int countt=0;
        for(int i=1;i<=1000;i++) if(g[i]&&sett[i]==i) countt++;
//        printf("countt %d\n",countt);
        if(countt > 1) flag=0;
//        printf("flag %d\n",flag
                 if(flag) printf("Case %d is a tree.\n",cases);
                    else printf("Case %d is not a tree.\n",cases);
        cases++;
//        for(int i=1;i<=10;i++)
//            printf("%d ",i);
//             printf("\n");
//             for(int i=1;i<=10;i++)
//            printf("%d ",sett[i]);
//        printf("\n");
    }
    return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/a197p/article/details/47065541