#include<bits/stdc++.h>
const int maxn = 10001;
int father[maxn];
void init(int father[], int n) {
for (int i = 1; i <= n; i++) {
father[i] = i;
}
}
int findFather1(int x) {//返回元素x所在集合的根节点
while (x != father[x]) {//如果不是根节点,继续循环
x = father[x];//获得自己父亲的根节点
}
return x;
}
int findFather2(int x) {//递归实现返回元素x所在集合的根节点
if (x == father[x]) return x;//如果找到根节点,则返回根节点编号
else return findFather2(father[x]);
}
int findFather3(int x) {
//由于x在下面的while中会变成根节点,因此先把原来的x保存
int a = x;
while (x != father[x]) {//寻找根节点
x = father[x];
}
//把路径上所有的father都改为根节点
while (a != father[a]) {
int z = a;//因为a要被father[a]覆盖,因此先保存a的值,以修改father[a]
a = father[a];//a回溯父亲节点
father[z] = x;//将原先的结点a的父亲改为根节点x
}
return x;//返回根节点
}
int findFather4(int v) {
if (v == father[v]) return v;//找到根节点
else {
int F = findFather4(father[v]);//递归寻找father[v]的根节点
father[v] = F;//将根节点F赋值给father[v]
return F;//返回根节点F
}
}
void Union(int a, int b) {
int faA = findFather1(a);//查找a的根节点,记为faA
int faB = findFather1(b);//查找b的根节点,记为faB
if (faA != faB) {
father[faA] = faB;//合并它们
}
}
并查集的基本操作
最新推荐文章于 2024-08-19 17:10:15 发布