int find(int s[], int x) {
int root = x;
// 先找出根节点
while (s[x] >= 0) root = s[root];
// return root;
while (s[x] >= 0) {
// 如果不是则将节点接到根节点上
int tmp = s[x];
s[x] = root;
x = s[x];
}
return root;
}
void union(int s[], int root1, int root2) {
if (root1 == root2) return ;
// 都是负数 roo2小 所以 root2节点数更多
if (s[root1] > s[root2]) {
s[root2] += s[root1];
s[root1] = root1;
} else {
s[root1] += s[root2];
s[root2] = root1;
}
}
王道并查集代码
最新推荐文章于 2024-10-01 23:05:47 发布