此博客详细介绍了并查集的基本概念:并查集的初级应用及进阶
POJ1308:题意是输入每两个的数第二个的父亲是第一个数,判断输入结束之后是否是一颗树的结构。
#include<stdio.h>
int father[10020];
int Find_it(int x)
{
int temp = x,t;
while(father[temp] != temp)
temp = father[temp];
while(father[x] != x){
t = father[x];
father[x] = temp;
x = t;
}
return temp;
}
int main()
{
int nCase = 1;
while(1){
int flag = 1,x,y,i;
for(i = 1;i <= 10001; i++)
father[i] = i;
while(scanf("%d%d",&x,&y) != EOF){
if(x == 0 && y == 0)
break;
if(x == -1 && y == -1)
return 0;
int tx = Find_it(x);
int ty = Find_it(y);
if(tx == ty)
flag = 0;
else father[ty] = tx;
}
int k = 0;
for(i = 1;i <= 10001; i++){
int temp = Find_it(i);
if(temp != i){
if(k == 0)
k = temp;
else if(k != temp){
flag = 0;
break;
}
}
}
if(flag)
printf("Case %d is a tree.\n",nCase++);
else printf("Case %d is not a tree.\n",nCase++);
}
return 0;
}

本文通过POJ1308题目实例介绍并查集的实现方式,并演示如何使用并查集判断输入数据是否构成一棵树。文章提供了一段完整的C语言代码,包括并查集的查找和合并操作。
135

被折叠的 条评论
为什么被折叠?



