//2364907     2010-12-05 00:06:08     Accepted     1268     C     0     416     VRS
//1268 Is it a Tree? 并查集
//利用并查集,一直合并,直到输入结束
//注意几点:1.空树也是树;2.森林不是树;3.重复输入会当成环,也不行;4.结点自身指向自身也算是环
#include<stdio.h>
#define bool int
#define  MAXNUM 32767

 

int father[MAXNUM];
int differentTreeNode[MAXNUM];

int Find(int x)
{
    if(father[x]==x)
        return x;
    father[x]=Find(father[x]);
    return father[x];
}

void Union(int x,int y)
{
    int rootx,rooty;
    rootx=Find(x);
    rooty=Find(y);
    father[y]=x;
}

int main()
{
    int x,y;
    int rootx,rooty;
    int testcase,i,k;
    bool res;
    testcase=1;
    while(scanf("%d%d",&x,&y) && !(x<0 && y<0))
    {
        res=1;k=0;
        for(i=1;i<MAXNUM;i++)
            father[i]=i;

        while(!(x==0 && y==0))
        {
            //指向自身的形成环
            if(x==y)
                res=0;
            differentTreeNode[k++]=y;
            rootx=Find(x);
            rooty=Find(y);
            if(rootx==rooty)
                res=0;
            else
            {
                if(y==rooty)
                    Union(x,y);
                else
                    res=0;
            }
            scanf("%d%d",&x,&y);
        }
        //这里是在上面生成树的基础上,判断是否存在森林
        rootx=Find(differentTreeNode[0]);
        for(i=0;i<k;i++)
            if(Find(differentTreeNode[i])!=rootx)
                res=0;
        if(res)
            printf("Case %d is a tree.\n",testcase++);
        else
            printf("Case %d is not a tree.\n",testcase++);
    }
    return 0;
}

posted on 2010-12-08 20:46  VRS  阅读(217)  评论(0编辑  收藏  举报