Pagini recente » Cod sursa (job #1756797) | Cod sursa (job #1043086) | Clasament preoni61b | Cod sursa (job #2327113) | Cod sursa (job #2759132)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 100003;
const int LOG = 16;
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(N) solution
if(depth[x] < depth[y])swap(x,y);
while(depth[x] > depth[y])
x = up[x][0];
if(x==y)return x;
while(x!=y){
x=up[x][0];
y=up[y][0];
}
return x;
}
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;
}