Skip to content

Commit 077625f

Browse files
committed
disjoint set
1 parent d6de773 commit 077625f

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
2+
/*
3+
Disjoint set example of find and union
4+
5+
Question Url : https://www.hackerrank.com/challenges/merging-communities/problem
6+
7+
*/
8+
9+
#include <bits/stdc++.h>
10+
11+
using namespace std;
12+
13+
long find(int x,vector<int>&a)
14+
{
15+
while(1)
16+
{
17+
if(a[x]<0)
18+
{
19+
return x;
20+
}
21+
else
22+
{
23+
x=a[x];
24+
}
25+
}
26+
}
27+
int main()
28+
{
29+
int n;
30+
cin>>n;
31+
vector<int>arr(n+1,-1);
32+
int m;
33+
cin>>m;
34+
int i,j,x;
35+
char qt;
36+
long p1,p2;
37+
while(m--)
38+
{
39+
cin>>qt;
40+
if(qt=='M')
41+
{
42+
43+
cin>>i>>j;
44+
p1=find(i,arr);
45+
p2=find(j,arr);
46+
if(p1!=p2)
47+
{
48+
arr[p1]=arr[p1]+arr[p2];
49+
arr[p2]=p1; //making p1 as parrent of that node;
50+
arr[j]=p1; //collapsing the tree what i have learned to minimize the time to find the parent;
51+
52+
}
53+
54+
}
55+
else
56+
{
57+
cin>>x;
58+
59+
cout<<abs(arr[find(x,arr)])<<endl; // finding how many of them are in a group basically union set
60+
}
61+
}
62+
63+
64+
65+
66+
return 0;
67+
}
68+
69+
70+

0 commit comments

Comments
 (0)