poj1308 并查集

时间:2020-11-28 18:12:40

比较恶心

1: 0 0 空树是一棵树
2: 1 1 0 0 不是树
3: 1 2 1 2 0 0 不是树...
4: 1 2 2 3 4 5 不是树 森林不算是树
5: 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 错
6: 1 2 2 1 0 0 也是错误的
#include<stdio.h>
#include<string.h>
int pa[],a[],b[],n,in[],map[],hash[];
void init()
{
for(int i=;i<=n;i++)
{
pa[i]=i;
}
}
int find(int x)
{
if(x!=pa[x])
pa[x]=find(pa[x]);
return pa[x];
}
int main()
{
int i,j,flag,ff=;
while(scanf("%d%d",&a[],&b[])!=EOF)
{
j=;
memset(hash,,sizeof(hash));
memset(map,,sizeof(map));
memset(in,,sizeof(in));
if(!hash[a[]])
map[j++]=a[];
if(!hash[b[]])
map[j++]=b[];
if(a[]==&&b[]==)
{
printf("Case %d is a tree.\n",++ff);
continue;
}
n=;
flag=;
if(a[]<&&b[]<)
break;
in[a[]]++,in[b[]]++;
if(a[] > n) n = a[];
if(b[] > n) n = b[];
i=;
while()
{
i++;
scanf("%d %d",&a[i],&b[i]);
if(a[i]==&&b[i]==)
break;
if(!hash[a[i]])
{
hash[a[i]]=;
map[j++]=a[i];
}
if(!hash[b[i]])
{
map[j++]=b[i];
hash[b[i]]=;
}
if(a[i] > n) n = a[i];
if(b[i] > n) n = b[i];
}
int num=j;
//for(j=0;j<num;j++)
// printf("%d ",map[j]);
//printf("\n");
int len=i;
init();
for(i=;i<len;i++)
{
int x,y;
x=find(a[i]);
y=find(b[i]);
if(x!=y)
{
pa[x]=y;
}
else
flag=;
}
int ans=;
for(i=;i<num;i++)
{
if(pa[map[i]]==map[i])
{
ans++;
}
}
if(ans>)
flag=;
if(flag)
printf("Case %d is a tree.\n",++ff);
else
printf("Case %d is not a tree.\n",++ff);
}
}