#include<cstdio>
//并查集用数组实现
//father[a] = b, 元素a的父亲结点为b
//father[i] = i, 元素i是该集合的根结点,同一个集合只存在一个根结点
const int N = 100;
int father[N] = {0};
int findFather(int x){
while(x != father[x]){
x = father[x];
}
return x;
}
//递归实现
int findFather2(int x){
if(x == father[x]) return x;
else return findFather2(father[x]);
}
//合并两个集合
void Union(int a, int b){
int faA = findFather(a);
int faB = findFather(b);
if(faA != faB){ //如果不属于同一个集合
father[faA] = faB; //合并它们
}
}
//路径压缩,把当前查询结点的路径上的所有结点的父亲都指向根结点
int findFather3(int x){
int a = x;
while(x != father[x]){
x = father[x];
}
//到这里,x存放的是根结点
while(a != father[a]){
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
//递归实现
int findFather4(int v){
if(v == father[v]) return v;
else {
int F = findFather4(father[v]);
father[v] = F;
return F;
}
}
int main(){
for(int i = 1; i <= N; i++){
father[i] = i; //初始化,每个元素都是独立的一个集合
}
father[1] = 1;
father[2] = 1;
father[3] = 2;
father[4] = 2;
father[5] = 5;
father[6] = 5;
printf("%d ", findFather(3));
printf("%d\n", findFather(6));
Union(3, 6);
printf("%d ", findFather(3));
printf("%d\n", findFather(6));
printf("%d\n", findFather4(4));
printf("%d ", father[1]);
printf("%d ", father[2]);
printf("%d\n", father[3]);
printf("%d ", father[5]);
printf("%d\n", father[6]);
return 0;
}
并查集的基本操作
本文详细介绍并查集数据结构的数组实现,包括findFather、findFather2、Union操作,以及路径压缩方法findFather3和findFather4。通过实例展示了如何合并集合和优化查询效率。
摘要由CSDN通过智能技术生成