-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathDsu.cpp
44 lines (35 loc) · 848 Bytes
/
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
// This is implementation of DSU data structure in C++
struct DSU {
vector<int> parent;
vector<int> size;
void make_set (int v) {
parent[v] = v;
size[v] = 1;
}
DSU(int N){
parent.assign(N+1,0);
size.assign(N+1,0);
for(int i=1; i<=N; i++)
make_set(i) ;
}
int find_set (int v) {
if (v == parent[v])
return v;
return parent[v] = find_set (parent[v]);
}
bool union_sets (int a, int b) {
a = find_set (a);
b = find_set (b);
if (a != b) {
if (size[a] < size[b])
swap (a, b);
parent[b] = a;
size[a]+=size[b] ;
return true ;
}
return false ;
}
int size_of(int node){
return size[find_set(node)] ;
}
};