Pagini recente » Cod sursa (job #423321) | Cod sursa (job #2433363) | Cod sursa (job #1890660) | Cod sursa (job #1170737) | Cod sursa (job #2327295)
#include<bits/stdc++.h>
#define N 100001
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
vector<int> a[N];
int d[N], dp[N][18];
void dfs(int i){
for(auto it:a[i]){
if(!d[it]){
d[it]=d[i]+1;
dp[it][0]=i;
dfs(it);
}
}
}
int main(){
int n,m,i,h,j,x,y,z;
in>>n>>m;
h=log(n);
for(i=1; i<n; ++i){
in>>x;
a[x].push_back(i+1);
}
dfs(1);
for(i=1; i<=h; ++i)
for(j=1; j<=n; ++j)
dp[j][i]=dp[dp[j][i-1]][i-1];
while(m--){
in>>x>>y;
if(d[x]>d[y]) swap(x,y);
z=d[y]-d[x];
for(i=h; i>=0 && z; --i){
if(z-(1<<i)>=0){
z-=(1<<i);
y=dp[y][i];
}
}
if(x==y){
out<<x<<"\n";
continue;
}
for(i=h; i>=0; --i){
if(dp[x][i]!=dp[y][i]){
x=dp[x][i];
y=dp[y][i];
}
}
out<<dp[x][0]<<"\n";
}
return 0;
}