- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathLCA.cpp
77 lines (68 loc) · 1.41 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
// Program to find "Least Common Ancestor" of two nodes by "Binary Lifting Technique"
#include<bits/stdc++.h>
usingnamespacestd;
int n, l, timer;
vector<vector<int>> adj;
vector<int> tin, tout;
vector<vector<int>> up;
voiddfs(int v, int p)
{
tin[v] = ++timer;
up[v][0] = p;
for (int i = 1; i <= l; ++i)
up[v][i] = up[up[v][i-1]][i-1];
for (int u : adj[v]) {
if (u != p)
dfs(u, v);
}
tout[v] = ++timer;
}
boolis_ancestor(int u, int v)
{
return tin[u] <= tin[v] and tout[u] >= tout[v];
}
intlca(int u, int v)
{
if (is_ancestor(u, v))
return u;
if (is_ancestor(v, u))
return v;
for (int i = l; i >= 0; --i) {
if (!is_ancestor(up[u][i], v))
u = up[u][i];
}
return up[u][0];
}
voidpreprocess(int root) {
tin.resize(n);
tout.resize(n);
timer = 0;
l = ceil(log2(n));
up.assign(n, vector<int>(l + 1));
dfs(root, root);
}
voidsolve(){
int q;
cin>>n>>q;
adj.resize(n + 1);
for(int i = 1;i < n;i++){
int x;
cin>>x;
x--;
adj[x].push_back(i);
adj[i].push_back(x);
}
preprocess(0);
while(q--){
int x, y;
cin>>x>>y;
x--;y--;
int ans = lca(x, y);
cout<<ans + 1<<endl;
}
}
intmain()
{
solve();
return0;
}