-
Notifications
You must be signed in to change notification settings - Fork 2
/
DSU.cpp
51 lines (40 loc) · 1010 Bytes
/
DSU.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*8<{=============~ BEGIN DSU ~===============>8*/
/*8<
@Title:
DSU / UFDS
@Usage:
You may discomment the commented parts to
find online which nodes belong to each
set, it makes the $union\_set$ method cost
$O(log^2)$ instead $O(A)$
>8*/
struct DSU {
vi ps, sz;
// vector<unordered_set<int>> sts;
DSU(int N)
: ps(N + 1),
sz(N, 1) /*, sts(N) */
{
iota(ps.begin(), ps.end(), 0);
// for (int i = 0; i < N; i++)
// sts[i].insert(i);
}
int find_set(int x) {
return ps[x] == x ? x
: ps[x] = find_set(ps[x]);
}
int size(int u) { return sz[find_set(u)]; }
bool same_set(int x, int y) {
return find_set(x) == find_set(y);
}
void union_set(int x, int y) {
if (same_set(x, y)) return;
int px = find_set(x);
int py = find_set(y);
if (sz[px] < sz[py]) swap(px, py);
ps[py] = px;
sz[px] += sz[py];
// sts[px].merge(sts[py]);
}
};
/*8<===============~ END DSU ~===============}>8*/