-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLCA.cpp
More file actions
95 lines (88 loc) · 1.97 KB
/
Copy pathLCA.cpp
File metadata and controls
95 lines (88 loc) · 1.97 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
92
93
94
95
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <cstring>
#include <iomanip>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <string>
#include <vector>
#include <new>
#include <bitset>
#include <ctime>
#include <stdint.h>
#include <unistd.h>
using namespace std;
#define ll long long int
#define INF 1000000000
#define PI acos(-1.0)
#define EPS 1e-9
template <typename X> X gcd(X a, X b){if(!b)return a; else return gcd(b, a%b);}
typedef vector<int> vi;
typedef pair<int, int> ii;
const int N = 1010;
int t, pv[N], le[N], T, pr[N][11], n, i, j, c, x, y, cs=1, fin[N], fout[N], q;
vector<int> g[N];
bool vis[N];
//O(n), O(sqrt(n)) dp algorithm
void dfs(int u){
fin[u]=++T;
vis[u]=true;
for(int j=0;j<(int)g[u].size();++j){
int v=g[u][j];
if(!vis[v]){
pv[v]=u;
le[v]=le[u]+1;
dfs(v);
}
}
fout[u]=++T;
}
bool anc(int x, int y){
return ((fin[x]<=fin[y]) && (fout[y]<=fout[x]));
}
int lca(int x, int y){
if(anc(x, y))
return x;
for(j=10;j>=0;--j)
if(!anc(pr[x][j], y))
x=pr[x][j];
return pv[x];
}
int main(){
scanf("%d", &t);
while(t--){
T=1, pv[1]=1, le[1]=1;
scanf("%d", &n);
for(i=1;i<=n;++i)
g[i].clear(), vis[i]=false;
for(i=1;i<=n;++i){
scanf("%d", &c);
while(c--){
scanf("%d", &x);
g[i].push_back(x);
g[x].push_back(i);
}
}
dfs(1);
for(i=1;i<=n;++i)
pr[i][0]=pv[i];
for(j=1;j<=10;++j)
for(i=1;i<=n;++i)
pr[i][j]=pr[pr[i][j-1]][j-1];
scanf("%d", &q);
printf("Case %d:\n", cs++);
while(q--){
scanf("%d %d", &x, &y);
if(le[x]>le[y])
swap(x, y);
printf("%d\n", lca(x, y));
}
}
return 0;
}