并查集
int find(int t)//poj 1213
{
if(F[t]==-1) return t;
return F[t]=find(F[t]);
}
void bing(int a,int b)
{
int t1=find(a);
int t2=find(b);
if(t1!=t2) F[t1]=t2;
}
main()
{
……
int res=0;
for(int i=1;i<=n;i++)
if(F[i]==-1) res++;
printf("%d\n",res);
}void bing(int x,int y)//poj1856
{
int rootx=getfather(x);
int rooty=getfather(y);
if(rootx!=rooty)
{
if(fatherson[rootx]>=fatherson[rooty]) // 这就是要比较了
{
father[rooty]=rootx;
fatherson[rootx]+=fatherson[rooty];
}
else
{
father[rootx]=rooty;
fatherson[rooty]+=fatherson[rootx];
}
}
else
return ;
}
本文详细介绍了并查集算法的基本概念及其在解决图论问题中的应用。通过两个具体的实例(poj1213和poj1856),展示了如何实现并查集的数据结构,包括查找根节点的方法及如何进行集合合并操作。此外,还讨论了加权并查集中如何维护子树大小以优化合并过程。
5012

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



