-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSU.cpp
More file actions
38 lines (37 loc) · 731 Bytes
/
Copy pathDSU.cpp
File metadata and controls
38 lines (37 loc) · 731 Bytes
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
/**
* Author: Kevin Li
* Lang: C++
* Description: DSU by Rank implementation
*/
struct dsu {
int n;
int *p, *r;
dsu () {}
dsu (int _n) : n(_n) {
p = new int[n];
r = new int[n];
preprocess();
}
void preprocess() {
for (int i = 0; i < n; i++) {
p[i] = i;
r[i] = 0;
}
}
int find(int i) {
if (i != p[i]) p[i] = find(p[i]);
return p[i];
}
void merge(int i, int j) {
int ic = find(i);
int jc = find(j);
if (r[ic] < r[jc]) {
p[ic] = jc;
} else if (r[ic] > r[jc]) {
p[jc] = ic;
} else {
p[jc] = ic;
r[ic]++;
}
}
};