-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsu.cpp
52 lines (40 loc) · 821 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
52
#include <cassert>
#include <vector>
struct DSU {
private:
int _n;
std::vector<int> parent, size;
public:
DSU() : _n(0) {}
DSU(int n) : _n(n) {
parent.resize(_n, -1);
size.resize(_n, -1);
}
void add(int x) {
parent[x] = x;
size[x] = 1;
}
int leader(int x) {
assert(0 <= x && x < _n);
if (parent[x] == x)
return x;
return parent[x] = leader(parent[x]);
}
int merge(int a, int b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
int x = leader(a), y = leader(b);
if (x == y)
return x;
if (parent[x] < parent[y])
std::swap(x, y);
size[x] += size[y];
parent[y] = x;
return x;
}
bool same(int a, int b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
return leader(a) == leader(b);
}
};