-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDSU.cpp
53 lines (45 loc) · 1.07 KB
/
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
53
#include<bits/stdc++.h>
using namespace std;
class DSU {
public:
vector<int> p, r, sz;
int n;
DSU() {
n = 0;
}
DSU(int _n) {
n = _n;
p = r = sz = vector<int>(n, 1);
for(int i = 0; i < n; i++) p[i] = i;
}
int find(int x) {
assert(0 <= x and x < n);
int y = x;
while(x != p[x]) x = p[x];
while(y != p[y]) {
int z = p[y];
p[y] = x;
y = z;
}
return x;
}
void join(int x, int y) {
assert(0 <= x and x < n and 0 <= y and y < n);
x = find(x), y = find(y);
if(x == y) return;
if(r[x] > r[y]) swap(x, y); // for rank heuristics
// if(sz[x] > sz[y]) swap(x, y); // to size heuristics
p[x] = y;
sz[y] += sz[x];
r[y] += r[x] == r[y];
}
};
// TODO:
// 1. Add min, max to each components
// 2. Find the total number of components in O(1)
// 3. Make it more general using ids and template
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}