forked from chandrikadeb7/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Disjoint_Sets.cpp
65 lines (59 loc) · 1017 Bytes
/
Disjoint_Sets.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
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
vector<ll> parent, size;
void make_set(ll n)
{
parent.resize(n);
size.resize(n);
for(ll i=0; i<n; i++)
{
parent[i]=i;
size[i]=1;
}
}
ll find(ll x)
{
if(parent[x]==x)
return x;
return parent[x]=find(parent[x]);
}
void union_sets(ll x, ll y)
{
ll a=find(x), b=find(y);
if(a!=b)
{
if(size[a]<size[b])
swap(a, b);
parent[b]=a;
size[a]+=size[b];
}
}
void print(ll n)
{
unordered_map<ll, vector<ll>> m;
for(ll i=0; i<n; i++)
m[parent[i]].pb(i);
for(auto y:m)
{
for(auto x:y.second)
cout<<x<<" ";
cout<<endl;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll n=5;
make_set(n);
union_sets(0, 1);
union_sets(2, 3);
union_sets(4, 3);
union_sets(2, 3);
print(n);
return 0;
}