-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnionFind.cpp
More file actions
31 lines (31 loc) · 1.07 KB
/
UnionFind.cpp
File metadata and controls
31 lines (31 loc) · 1.07 KB
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
struct UnionFind {
int n;
vector<int> parent, rank, num;
int find(int x) {
if (parent[x] == x) return x;
return parent[x] = find(parent[x]);
}
UnionFind(int n_) {
n = n_;
parent.resize(n);
for (int i = 0; i < n; i ++) parent[i] = i;
rank.assign(n, 0);
num.assign(n, 1);
}
void unite(int x, int y) {
if ((x = find(x)) != (y = find(y))) {
if (rank[x] < rank[y]) {
parent[x] = y;
num[y] += num[x];
} else {
parent[y] = x;
if (rank[x] == rank[y]) rank[x] ++;
num[x] += num[y];
}
n --;
}
}
bool same(int x, int y) { return find(x) == find(y); }
int get() { return n; }
int get(int x) { return num[find(x)]; }
};