forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDSU.cpp
62 lines (56 loc) · 1.43 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
// DSU by size
class dsu{
public:
vector<int> parent, size;
dsu(int n){
parent.resize(n);
size.resize(n, 1);
for(int i = 0; i < n; i++) parent[i] = i;
}
int findUParent(int node){
if(parent[node] == node) return node;
return parent[node] = findUParent(parent[node]);
}
void unionBySize(int u, int v){
int pu = findUParent(u);
int pv = findUParent(v);
if(pu == pv) return;
if(size[pu] >= size[pv]){
size[pu] += size[pv];
parent[pv] = pu;
}
else if(size[pu] < size[pv]){
size[pv] += size[pu];
parent[pu] = pv;
}
}
};
// DSU by rank;
class dsu{
vector<int> rank, parent;
public:
dsu(int n){
rank.resize(n, 0);
parent.resize(n);
for(int i = 0; i < n; i++) parent[i] = i;
}
int findUParent(int node){
if(node == parent[node]) return node;
return parent[node] = findUParent(parent[node]);
}
void unionByRank(int u, int v){
int parentU = findUParent(u);
int parentV = findUParent(v);
if(parentU == parentV) return;
if(rank[parentU] < rank[parentV]){
parent[parentU] = parentV;
}
else if(rank[parentU] > rank[parentV]){
parent[parentV] = parentU;
}
else{
parent[parentU] = parentV;
rank[parentV]++;
}
}
};