实现

包括路径压缩与按秩合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class UnionFind {
public:
UnionFind(int n) {
f.assign(n + 1, 0);
rank.assign(n + 1, 1);

for(int i = 0; i <= n; i++) {
f[i] = i;
}
}

int find(int x) {
return x == f[x] ? x : (f[x] = find(f[x]));
}

// 函数名不能用union,会与c++关键字冲突
void merge(int a, int b) {
int x = find(a), y = find(b);
if(rank[x] <= rank[y]) {
f[x] = y;
} else {
f[y] = x;
}
if(rank[x] == rank[y] && x != y) {
rank[y]++;
}
}

bool connected(int a, int b) {
int roota = find(a), rootb = find(b);
return roota == rootb;
}

private:
vector<int> f, rank;
};

相关题目

  1. 除法求值

  2. 由斜杠划分区域

  3. 飞地的数量

  4. 交换字符串中的元素

  5. 找到最小生成树里的关键边和伪关键边

  6. 保证图可完全遍历

参考