Pagini recente » Cod sursa (job #1024530) | Cod sursa (job #681789) | Cod sursa (job #1653206) | Cod sursa (job #1757744) | Cod sursa (job #2758990)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 100003;
const int LOG = 17;
int n,m;
int depth[NMAX];
int up[NMAX][LOG+1];
vector<int>v[NMAX];
void dfs(int nod){
for(int child:v[nod]){
depth[child]=depth[nod]+1;
up[child][0]=nod;
for(int i=1;i<=LOG;i++)
up[child][i]=up[up[child][i-1]][i-1];
dfs(child);
}
}
int get_lca(int x,int y){// O(log N) solution
if(depth[x] < depth[y])swap(x,y);
int k = depth[x] - depth[y];
for(int j=LOG;j>=0;j--)
if(k&(1<<j))
x = up[x][j];
if(x==y)return x;
for(int i=LOG;i>=0;i--)
if(up[x][i]!=up[y][i]){
x = up[x][i];
y = up[y][i];
}
return up[x][0];
}
int main(){
freopen("lca.in","r",stdin);
freopen("lca.out","w", stdout);
scanf("%d %d",&n,&m);
for(int i=1;i<n;i++){
int x;
scanf("%d",&x);
v[x].push_back(i+1);
}
dfs(1);
while(m--){
int x,y;
scanf("%d %d",&x,&y);
printf("%d\n",get_lca(x,y) );
}
return 0;
}