路径压缩 + 按秩合并
时间复杂度 $ O ( \alpha (n) ) $
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| void init() {
for (int i = 1; i <= n; i++) f[i] = i, rk[i] = 1;
}
int find(int x) {
if (x != f[x]) f[x] = find(f[x]);
return f[x];
}
void merge(int x, int y) {
x = find(x);
y = find(y);
if (rk[x] > rk[y])
f[y] = x;
else {
f[x] = y;
if (rk[x] == rk[y]) rk[y]++;
}
}
bool same(int x, int y) { return find(x) == find(y); }
|