-
Notifications
You must be signed in to change notification settings - Fork 0
/
LCA.cpp
77 lines (70 loc) · 1.12 KB
/
LCA.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
68
69
70
71
72
73
74
75
76
77
#include <iostream>
using namespace std;
int Arr[1001];
bool visited[1001];
int t,nodes,child,query,x,y,z1,z2,i;
int casex=1;
void initialize()
{
for(int i = 0;i<=nodes;i++)
{
Arr[ i ] = i ;
visited[i]=false;
}
}
void initializeb()
{
for(int i = 0;i<=nodes;i++)
{
visited[i]=false;
}
}
int lca(int a,int b)
{
while(Arr[ a ] != a) //chase parent of current element until it reaches root.
{
visited[a]=true;
a = Arr[ a ];
}
while(Arr[ b ] != b) //chase parent of current element until it reaches root.
{
if(visited[b]==true)
{
break;
}
b = Arr[ b ];
}
return b;
}
int unionx(int A ,int B)
{
Arr[ B ] = A ; //setting parent of root(B) as root(A).
}
int main() {
// your code goes here
cin>>t;
while(t--)
{
cout<<"Case "<<casex<<":"<<endl;
cin>>nodes;
initialize();
for(i=1;i<=nodes;i++)
{
cin>>x;
while(x--)
{
cin>>y;
unionx(i,y);
}
}
cin>>query;
while(query--)
{
initializeb();
cin>>z1>>z2;
cout<<lca(z1,z2)<<endl;
}
casex++;
}
return 0;
}