图片示意
代码
#include <bits/stdc++.h>
using namespace std;
int findFather(int v);
int find(int v);
void Union(int x, int y);
int parent[4];
int findFather(int v) {
if (parent[v] != v) {
parent[v] = findFather(parent[v]);
}
return parent[v];
}
int find(int v) {
if (parent[v] == v) {
return v;
}
return find(parent[v]);
}
void Union(int x, int y) {
parent[find(x)] = find(y);
/// 带路径压缩的方法
/// parent[findFather(x)] = findFather(y);
}
int main() {
for (int i = 0; i < 4; i++) {
parent[i] = i;
}
Union(0, 1);
Union(1, 2);
Union(2, 3);
for (auto item: parent) {
printf("%d ", item);
}
return 0;
}
演示ppt下载
链接:https://pan.baidu.com/s/1hmeGpOmsJ99aOIWH15wQpw
提取码:gqqy