poj 1308 Is It A Tree?(并查集)

思路同hdu 1272

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

#define MAXN 1005

int fa[MAXN],sign[MAXN],flag;

int set_find(int d)
{
    if(fa[d]<0)return d;
    return fa[d]=set_find(fa[d]);
}

void set_join(int x,int y)
{
    x=set_find(x);
    y=set_find(y);
    if(x!=y)fa[x]=y;
    else flag=0;//同一个父节点,成环
}

int main()
{
    int i,a,b,cas=1;
    while(cin>>a>>b)
    {
        if(a==-1&&b==-1) break;
        if(a==0&&b==0)
        {
            cout<<"Case "<<cas++<<" is a tree."<<endl;
            continue;
        }
        for(i=1; i<MAXN; i++)
        {
            fa[i]=-1;
            sign[i]=0;
        }
        sign[a]=sign[b]=1;
        flag=1;
        set_join(a,b);
        while(cin>>a>>b)
        {
            if(a==0&&b==0) break;
            set_join(a,b);
            sign[a]=sign[b]=1;
        }
        int k=0;
        for(i=1; i<MAXN; i++)
        {
            if(sign[i]&&fa[i]==-1) //判断根节点k数目
                k++;
            if(k>1) flag=0;
        }
        if(flag) cout<<"Case "<<cas++<<" is a tree."<<endl;
        else cout<<"Case "<<cas++<<" is not a tree."<<endl;
    }
    return 0;
}


你可能感兴趣的:(poj 1308 Is It A Tree?(并查集))