并查集【学习记录】
参考链接
题目地址:https://ac.nowcoder.com/acm/contest/10138/F
感谢大佬!
简单的并查集由三部分组成
- find
- join
- 路径压缩
find 函数的实现:
//find 函数的实现
int find(int x){
while(pre[x]!=x){
x=pre[x]
}
return x;
}
//效率很低,一般要配合状态压缩使用.
join函数的实现:
//join
void join(int x,int y)
{
int fx=find(x);
int fy=find(y);
pre[fx]=fy;
}
仅仅上面两个函数,就足以完成比赛的F题目
路径压缩:
int find_pre(int x) //查找结点x的根结点
{
if(pre[x] == x) //递归出口:x的上级为x本身,即x为根结点
return x;
return pre[x] = find_pre(pre[x]); //此代码相当于先找到根结点rootx,然后pre[x]=rootx
}
//简化为
int find_pre(int x)
{
return pre[x]==x ? x : pre[x]=find_pre(pre[x]);
}
模板:
//初始化
void (int n)
{
for(int i = 0 ;i < n; i++)
pre[i]=i;
}
//find
int find(int x)
{
return pre[x] == x ? x : pre[x] = find(pre[x]);
}
//join
void join(int x,int y)
{
int fx=find(x);
int fy=find(y);
pre[fx]=fy;
}