forked from spandey1296/Learn-Share-Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsu.cpp
72 lines (63 loc) ยท 1.12 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
63
64
65
66
67
68
69
70
71
72
//Implementation of disjoint set union data structure
//with path compression & union by rank optimisations
#include<bits/stdc++.h>
using namespace std;
void make_set(vector<int> &rep, int v){
rep[v] = v;
rank[v] = 0;
}
//Path Compression Optimisation
int find(vector<int> &rep, int v){
// if(rep[v]==v)
// return v;
// rep[v] = find(rep, rep[v]);
// return rep[v];
vector<int> list;
while(1){
if(rep[v]==v)
break;
list.push_back(v);
v = rep[v];
}
for(auto n: list)
rep[n] = v;
return v;
}
//Union by rank optimisation
void union(vector<int> &rep, vector<int>& rank, int a, int b){
a = find(rep, a);
b = find(rep, b);
if(a!=b){
if(rank[a]<rank[b])
swap(a, b);
rep[b] = a;
if(rank[a]==rank[b])
rank[a]++;
}
}
void disunion(int nroot, vector<bool>& rm){
int p;
for(int i=0;i<N;++i)find(i);
for(int i=0;i<N;++i){
p=find(i);
if(rm[p]&&!rm[i]){
par[p]=i;
par[i]=i;
}
}
for(int i=0;i<N;++i)find(i);
for(int i=0;i<N;++i){
if(rm[i]){
par[i]=nroot;
rm[i]=0;
}
}
memset(rnk,0,sizeof(rnk));
for(int i=0;i<N;++i){
p=getPar(i);
if(p!=i)rnk[p]=1;
}
}
int main(){
return 0;
}