并查集模板
并查集模板
代码:
int father[N];//定义father数组,存储父亲节点
void init(int x)//初始化father数组
{
for(int i=1;i<=x;i++)
father[i]=i;
}
//并查集的核心,查找祖宗节点(根节点)
//路径优化版本是在查找的过程中将经过的结点都指向
//祖宗节点,在下一次查找到该节点时就只用查找一次
int find_father(int x)
{
/*
//递归
if(x!=father[x])
return find_father(father[x]);
return x;
*/
//递归版本 + 路径压缩
if(x!=father[x])
father[x]=find_father(father[x]);
return father[x];
/*
//非递归
while(x!=father[x])
x=father[x];
return x;
*/
/*
//非递归 + 路径压缩
int a=x;
while(x!=father[x])
x=father[x];
while(a!=father[a])
{
int b=a;
a=father[a];
father[b]=x;
}
return x;
*/
}
//将 a,b 合并到一个并查集中
void merge_(int a,int b)
{
int fa=find_father(a);
int fb=find_father(b);
if(fa!=fb)
father[fa]=fb;
//father[fb]=fa; 无影响
}