Pagini recente » Cod sursa (job #1971540) | Cod sursa (job #2584741) | Cod sursa (job #2331390) | Cod sursa (job #1025909) | Cod sursa (job #2786614)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
int level[100005];
int dp[18][100005];
int n, q, x, y, stramos_x, stramos_y, sol;
int st, up, dr;
int stramos(int nod, int dist){
int p2=0;
while(dist > 0){
if(dist&1)
nod = dp[p2][nod];
p2++;
dist >>= 1;
}
return nod;
}
int main (){
fin>>n>>q;
dp[0][1]=0; level[1]=1;
for(int i=2; i<=n; i++){
fin>>dp[0][i];
level[i] = level[ dp[0][i] ] + 1;
}
for(int i=1; i<=17; i++)
for(int j=1; j<=n; j++)
dp[i][j] = dp[i-1][ dp[i-1][j] ];
while(q--){
fin>>x>>y;
if(level[x] > level[y])
swap(x, y);
x = stramos(x, level[y] - level[x]);
if(x == y){
fout<<x<<"\n";
continue;
}
st=1;
dr=level[x]-1;
while(st <= dr){
up=(dr-st)/2+st;
stramos_x = stramos(x, up);
stramos_y = stramos(y, up);
if(stramos_x == stramos_y){
sol=stramos_x;
dr=up-1;
}else
st=up+1;
}
fout<<sol<<"\n";
}
return 0;
}