forked from diptayan2k/Data-Structures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjoint-Set-Union.cpp
More file actions
91 lines (59 loc) · 1.29 KB
/
Disjoint-Set-Union.cpp
File metadata and controls
91 lines (59 loc) · 1.29 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include<bits/stdc++.h>
#define ll long long int
#define f(i,a,b) for(ll i=a;i<=b;i++)
#define g(i,a,b) for(ll i=a;i>=b;i--)
#define F first
#define vv vector
#define S second
#define mp make_pair
#define pb push_back
#define mh make_heap
#define ph push_heap
#define pq priority_queue
using namespace std;
ll size[1000001];
ll a[1000001];
void intialise(ll n)
{
f(i,0,n)
{
a[i]=i;
size[i]=1;
}
}
ll root(ll i)
{
ll j=i;
while(a[i]!=i)
{
i=a[i];
a[j]=i;
j=i;
}
return i;
}
void union_(ll x, ll y)
{
ll rootx=root(x);
ll rooty=root(y);
if(size[rooty]>size[rootx]) swap(x,y);
a[rooty]=rootx;
size[rootx]+=size[rooty];
}
bool check_connection(ll x, ll y)
{
ll rootx=root(x);
ll rooty=root(y);
if(rootx==rooty) return true;
else return false;
}
int main()
{
intialise(5);
if(check_connection(2,3)) cout<<"2 and 3 are connected before union"<<endl;
else cout<<"2 and 3 are not connected before union"<<endl;
union_(2,3);
if(check_connection(2,3)) cout<<"2 and 3 are connected after union"<<endl;
else cout<<"2 and 3 are not connected after union"<<endl;
}