-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathUnion+Find.cpp
More file actions
67 lines (62 loc) · 1.83 KB
/
Union+Find.cpp
File metadata and controls
67 lines (62 loc) · 1.83 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
#include<bits/stdc++.h>
using namespace std;
long long parent[20005];
long long n;
long long dist[20005];
long long ini()
{
for(long long i=1;i<=n;i++)
{
parent[i]=i;
dist[i]=0;
}
}
long long finds(long long a)
{
if(parent[a]!=a)
{
int x=parent[a];
parent[a]=finds(parent[a]); //Recursively call the function with the parent of �a� till you reach a terminal node. Then update the distances of each of the nodes on the return path and also their parent to point to that terminal node.
dist[a]+=dist[x];// a is the node for that iteration and x is its parent
}
return parent[a]; //returning parent[a] bcz we are doing parent[a]=parent[parent[a]]
}
long long uni(long long a,long long b)
{
// b=finds(b);
parent[a]=b;
dist[a]=abs(a-b)%1000;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(false);
long long t;
cin>>t;
while(t--)
{
// ini();
cin>>n;
ini();
char s;
cin>>s;
while(s!='O')
{
if(s=='E')
{
long long numb;
cin>>numb;
int x=finds(numb);
cout<<dist[numb]<<"\n";
}
else
{
long long a,b;
cin>>a>>b;
if(finds(a)!=finds(b))
uni(a,b);
}
cin>>s;
}
}
}