-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdsu.cpp
More file actions
47 lines (43 loc) · 822 Bytes
/
dsu.cpp
File metadata and controls
47 lines (43 loc) · 822 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
39
40
41
42
43
44
45
46
47
struct dsu {
int n;
vector<int> parent;
vector<int> count;
vector<int> rank;
vector<vector<int> edges;
void makeset(int rn) {
int n = rn;
edges.resize(n);
count.assign(n, 1);
rank.assign(n, 0);
parent.assign(n, 0);
rep(i, 0, n) parent[i] = i;
}
int findParent(int x) {
if (parent[x] == x)
return x;
else {
parent[x] = findParent(parent[x]);
return parent[x];
}
}
void merge(int x, int y) {
int p1 = findParent(x);
int p2 = findParent(y);
if (p1 == p2) return;
edges[x].pb(y);
edges[y].pb(x);
if (rank[p1] < rank[p2])
swap(p1, p2);
else if (rank[p1] == rank[p2])
rank[p2]++;
parent[p2] = p1;
count[p1] += count[p2];
return;
}
int size(int x) {
return count[findParent(x)];
}
bool issame(int x, int y) {
return findParent(x) == findParent(y);
}
};