poj 1308 (并查集)

#include<cstdio>
#include
<iostream>
using namespace std;
#define MAXN 1000
int father[MAXN];
int rank[MAXN];
int a[MAXN],b[MAXN];
void make_set(int x)
{
father[x]
=x;
rank[x]
=0;
}
int find_set(int x)
{
if(x==father[x]) return x;
return father[x]=find_set(father[x]);
}
void union_set(int x,int y)
{
int rx=find_set(x);
int ry=find_set(y);
father[ry]
=rx;

}
int main()
{
int CASE=0;
int ra,rb,n;
while(scanf("%d%d",&a[1],&b[1])!=EOF)
{
if(a[1]==-1&&b[1]==-1) return 0;
if(a[1]==0&&b[1]==0)
{
printf(
"Case %d is a tree.\n",++CASE);
continue;
}
int i=1;
while(1)
{
i
++;
scanf(
"%d%d",&a[i],&b[i]);
if(a[i]==0&&b[i]==0) break;
}
n
=i;
int ok=1;
for(i=1;i<MAXN;i++)
make_set(i);
for(i=1;i<n;i++)
{
ra
=find_set(a[i]);
rb
=find_set(b[i]);
if(ra==rb)
{
ok
=0;
break;
}
else
union_set(a[i],b[i]);
}
int s=find_set(a[1]);
for(i=1;i<n;i++)
{
ra
=find_set(a[i]);
rb
=find_set(b[i]);
if(s!=ra||s!=rb)
{
ok
=0;
break;
}

}
if(ok==1) printf("Case %d is a tree.\n",++CASE);
else printf("Case %d is not a tree.\n",++CASE);
}
}

posted on 2011-06-09 18:43  thinking001  阅读(115)  评论(0)    收藏  举报

导航