并查集

并查集(Disjoint Set)是一种用于处理元素分组及查询两个元素是否属于同一组的数据结构。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct DSU {
int n;
std::vector<int> f, cntv;
DSU(int size) : n(size), f(n), cntv(n, 1) {
std::iota(f.begin(), f.end(), 0);
}
int find(int x) {
return f[x] == x ? x : f[x] = find(f[x]);
}
bool same(int x, int y) { return find(x) == find(y); }
bool merge(int x, int y) {
x = find(x), y = find(y);
if (x == y) {
return false;
}
cntv[x] += cntv[y];
f[y] = x;
return true;
}
int cnt_v(int x) { return cntv[find(x)]; }
};