#include<stdio.h>
// 并查集代码实现
int pre[10];
void init(int S[]){
for(int i=0;i<10;i++){
S[i]=-1;
}
}
int find(int S[],int x){
while(S[x] >= 0) {
x = S[x];
}
return x;
}
void Union(int S[],int x, int y){
int fx = find(S,x);
int fy = find(S,y);
printf("%d的上级是%d\n",x,fx);
printf("%d的上级是%d\n",y,fy);
if(fx == fy){
printf("fx fy是同一上级");
return;
}else{
S[fx]=fy;
printf("%d 合并到 %d\n",y,x);
}
}
void showArr(){
for(int i=0;i<10;i++){
printf("%d = [%d]\n",i,pre[i]);
}
}
int main(void){
init(pre);
showArr();
// 6 -> 0
Union(pre,6,0);
Union(pre,7,0);
Union(pre,8,0);
//9 -> 1
Union(pre,9,1);
Union(pre,4,1);
Union(pre,1,0);
showArr();
/*
0 = [-1]
1 = [0]
2 = [-1]
3 = [-1]
4 = [1]
5 = [-1]
6 = [0]
7 = [0]
8 = [0]
9 = [1]
*/
return 0;
}
08-03
176
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)