-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdisjoint-set.cpp
More file actions
72 lines (57 loc) · 1.4 KB
/
disjoint-set.cpp
File metadata and controls
72 lines (57 loc) · 1.4 KB
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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double dbl;
#define fr(x,a,b) for(ll x=a;x<b;x++)
#define rf(x,a,b) for(ll x=a;x>b;x--)
#define pii pair<ll,ll>
#define PB push_back
#define MP make_pair
#define mod 1000000007
#define gmax LLONG_MAX
#define gmin LLONG_MIN
#define INF 2e9
#define N 100001
#define MAX(a,b,c) max(max(a,b),c)
#define MIN(a,b,c) min(min(a,b),c)
#define SZ(s) s.size()
#define MS(x,v) memset(x,v,sizeof(x))
ll par[N],rnk[N];
void createSet(ll n){
fr(i,0,n+1){
par[i]=i;
rnk[i]=0;
}
}
ll findSet(ll x){
if(par[x]!=x){
par[x]=par[par[x]];
x=par[x];
}
return x;
}
void mergeSet(ll x,ll y){
ll xx=findSet(x);
ll yy=findSet(y);
if(rnk[xx]>rnk[yy]) par[yy]=xx;
else par[xx]=yy;
if(rnk[xx]==rnk[yy]) rnk[yy]++;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
createSet(5);
cout<<"Initially\n";
fr(i,1,5+1) cout<<i<<" belongs to set:"<<findSet(i)<<"\n";
cout<<"\nAfter merging 1 and 2\n";
if(findSet(1)!=findSet(2)) mergeSet(1,2);
fr(i,1,5+1) cout<<i<<" belongs to set:"<<findSet(i)<<"\n";
cout<<"\nAfter merging 4 and 5\n";
if(findSet(5)!=findSet(4)) mergeSet(5,4);
fr(i,1,5+1) cout<<i<<" belongs to set:"<<findSet(i)<<"\n";
cout<<"\nAfter merging 1 and 4\n";
if(findSet(1)!=findSet(4)) mergeSet(1,4);
fr(i,1,5+1) cout<<i<<" belongs to set:"<<findSet(i)<<"\n";
return 0;
}