-
Notifications
You must be signed in to change notification settings - Fork 114
/
DSU.cpp
49 lines (42 loc) · 897 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
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;
class DSU{
private:
vector<int> parent,size;
public:
DSU(int n){
for(int i = 0;i <= n;i++) {
parent.push_back(i);
size.push_back(1);
}
}
public:
int findPar(int node) {
if(parent[node] == node) {
return node;
}
// Path compression --> log(n)
// Path compression and size --> O(4 x alpha)
return parent[node] = findPar(parent[node]);
}
public:
void Union(int u, int v){
int pu = findPar(u);
int pv = findPar(v);
if(pu == pv){
return;
}
if(size[pv] < size[pu]){
parent[pv] = pu;
size[pu] += size[pv];
}
else{
parent[pu] = pv;
size[pv] += size[pu];
}
}
}
int main() {
int n = 10;
DSU dsu(n);
}