-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathDisjoint Set Union.cpp
More file actions
50 lines (41 loc) · 744 Bytes
/
Disjoint Set Union.cpp
File metadata and controls
50 lines (41 loc) · 744 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
48
49
50
int parent[N], size[N];
int find(int v) {
if (v == parent[v])
return v;
return parent[v] = find(parent[v]);
}
void make(int v) {
parent[v] = v;
size[v] = 1;
}
void unite(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (size[a] < size[b])
swap(a, b);
parent[b] = a;
size[a] += size[b];
}
}
class dsu {
public:
vector<int> p;
int n;
dsu(int _n) : n(_n) {
p.resize(n);
iota(p.begin(), p.end(), 0);
}
inline int get(int x) {
return (x == p[x] ? x : (p[x] = get(p[x])));
}
inline bool unite(int x, int y) {
x = get(x);
y = get(y);
if (x != y) {
p[x] = y;
return true;
}
return false;
}
};