forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
findunion.cpp
70 lines (53 loc) · 1.1 KB
/
findunion.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
/*
Disjoint set example of find and union
Question Url : https://www.hackerrank.com/challenges/merging-communities/problem
*/
#include <bits/stdc++.h>
using namespace std;
long find(int x,vector<int>&a)
{
while(1)
{
if(a[x]<0)
{
return x;
}
else
{
x=a[x];
}
}
}
int main()
{
int n;
cin>>n;
vector<int>arr(n+1,-1);
int m;
cin>>m;
int i,j,x;
char qt;
long p1,p2;
while(m--)
{
cin>>qt;
if(qt=='M')
{
cin>>i>>j;
p1=find(i,arr);
p2=find(j,arr);
if(p1!=p2)
{
arr[p1]=arr[p1]+arr[p2];
arr[p2]=p1; //making p1 as parrent of that node;
arr[j]=p1; //collapsing the tree what i have learned to minimize the time to find the parent;
}
}
else
{
cin>>x;
cout<<abs(arr[find(x,arr)])<<endl; // finding how many of them are in a group basically union set
}
}
return 0;
}