-
Notifications
You must be signed in to change notification settings - Fork 1
/
DisjointSet.cpp
40 lines (39 loc) · 1.12 KB
/
DisjointSet.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
// Disjoint Set Template for its implementation
class DisjointSet{
public:
vector<int> rank, parent, size;
DisjointSet(int n){
rank.resize(n + 1, 0);
parent.resize(n + 1);
size.resize(n + 1, 1);
for(int i = 0; i<=n; i++) parent[i] = i;
}
int findUPar(int node){
if(node == parent[node]) return node;
return parent[node] = findUPar(parent[node]);
}
void unionByRank(int u, int v){
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if(ulp_u == ulp_v) return;
if(rank[ulp_u] < rank[ulp_v]) parent[ulp_u] = ulp_v;
else if(rank[ulp_u] > rank[ulp_v]) parent[ulp_v] = ulp_u;
else{
parent[ulp_v] = ulp_u;
rank[ulp_u]++;
}
}
void unionBySize(int u, int v){
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if(ulp_u == ulp_v) return;
if(size[ulp_u] < size[ulp_v]) {
parent[ulp_u] = ulp_v;
size[ulp_v] += size[ulp_u];
}
else{
parent[ulp_v] = ulp_u;
size[ulp_u] += size[ulp_v];
}
}
};