并查集
并查集
//按秩合并版
void merge(long long x,long long y)
{
x=find(x);
y=find(y);
if(h[x]==h[y])
{
s[x]=y;
h[y]++;
}else{
if(h[x]>h[y])
s[y]=x;
else s[x]=y;
}
}
//纯净版
//将y的集合合并到x的集合中
void merge(long long x,long long y)
{
long long a=find(x);
long long b=find(y);
s[b]=a;
}
//路径压缩:循环
//查询优化版,每次合并完将所有s[i]直接设置为根的值
long long find(int x)
{
int r=x;
while(s[r]!=r)
r=s[r];
int i=x,t;
while(i!=r)
{
t=i;
i=s[i];
s[t]=r;
}
return r;
}
//路径压缩:递归
int find(int x)
{
if(s[x]==x)
return s[x];
if(s[x]!=x)
s[x]=find(s[x]);
return s[x];
}

本文来自博客园,作者:多巴胺不耐受仿生人,转载请注明原文链接:https://www.cnblogs.com/VoidCoderTF/articles/15435476.html

浙公网安备 33010602011771号