Pagini recente » Cod sursa (job #2141904) | Cod sursa (job #2118810) | Cod sursa (job #1022411) | Borderou de evaluare (job #2258336) | Cod sursa (job #3164323)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int l[100005];
int f[100005];
int dp[18][100005];
int lg;
int dfs(int x){
if(l[x] != 0 || x == 1) return l[x];
l[x] = dfs( f[x] ) + 1;
return l[x];
}
int ancestor(int x, int lvl){
while(lvl > 0){
int p = 17;
while((1 << p) > lvl ) p--;
if( p >= lg ) return 0;
x = dp[p][x];
lvl -= (1 << p);
}
return x;
}
int main(){
cin.tie(0);ios::sync_with_stdio(0);
int n, q;
fin >> n >> q;
f[1] = 0;
for(int i = 2; i <= n; i++){
fin >> f[i];
}
for(int i = 1; i <= n; i++) dfs(i);
lg = 17;
for(int i = 1; i <= n; i++) dp[0][i] = f[i];
for(int i = 1; i < lg; i++){
for(int j = 1; j <= n; j++){
dp[i][j] = dp[i - 1][ dp[i - 1][j] ];
}
}
for(int ii = 0; ii < q; ii++){
int a, b; fin >> a >> b;
if(l[a] < l[b]){
b = ancestor(b, l[b] - l[a]);
}else if(l[a] > l[b]){
a = ancestor(a, l[a] - l[b]);
}
//cout << "a si b nivelate sunt acuma " << a << " si " << b << endl;
if(a == b){
fout << a << "\n";
continue;
}
int l = 0, r = n;
int last = 0;
while(l <= r){
int m = (l + r) / 2;
int aa = ancestor(a, m);
int bb = ancestor(b, m);
if(aa == bb){
r = m - 1;
last = aa;
}else{
l = m + 1;
}
}
fout << last << "\n";
}
return 0;
}