您的位置:首页 > 其它

POJ 1308 Is It A Tree?

2013-07-08 10:14 288 查看
大意:给出父子关系 看看能不能组成一棵树

#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

int rank[100005];
int set[100005];
int v[100005];

void init()
{
     for(int i=1;i<100000;i++)
     {
         set[i]=i;
         rank[i]=1;
     }
}

int find(int x)
{
    while(set[x]!=x)
    x=set[x];

    return x;
}

bool merge(int x,int y)
{
    int xx=find(x);
    int yy=find(y);
    if(xx==yy)return false;   //如果他们已经出现在一棵树中了   就返回FALSE
    if(rank[xx]>rank[yy])set[yy]=xx;
    else
    {
        set[xx]=yy;
        if(rank[xx]==rank[yy])rank[yy]++;
    }
    return true;
}

int main()
{
    int n,m;
    int Case=1;
    int cnt=0,i;
    bool flag=true;
    memset(v,0,sizeof(v));
    int max=0;
    int root;
    init();
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==-1 && m==-1)break;

        if(!m && !n)
        {
            for(i=1;i<=max;i++)
            if(set[i]==i && v[i]){cnt++;}   

            if(cnt!=1 && max!=0)flag=false;   //这个MAX!=0是判断 1 1 0 0 这个数据  空树也是树

   
            //printf("cnt == %d\n",cnt);
            if(!flag)printf("Case %d is not a tree.\n",Case++);
            else printf("Case %d is a tree.\n",Case++);

            memset(v,0,sizeof(v));
            max=0;
            cnt=0;
            flag=true;
            init();
        }
        else
        {
            max=max>n?max:n;
            max=max>m?max:m;
            v
=v[m]=1;//标记
            if(flag)flag=merge(n,m);   //只要记录下不满足的状态 
            //printf("flag == %d\n",flag);
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: