Pagini recente » Cod sursa (job #1961809) | Cod sursa (job #241770) | Cod sursa (job #2094283) | Cod sursa (job #166829) | Cod sursa (job #3040730)
#include <bits/stdc++.h>
using ll=long long;
#define S second
#define F first
#define endl '\n'
#define spid ios_base::sync_with_stdio(false);cin.tie(NULL);
const int mod=1e9+7;
const double pi=3.14159265359;
const int maxn=100001;
using namespace std;
int n,m,parent[maxn],depth[maxn];
vector<vector<int>> A(maxn,vector<int>());
int dp[19][maxn];
void deepfs(int i){
for(int j=0;j<A[i].size();j++){
if(A[i][j]!=parent[i]){
depth[A[i][j]]=depth[i]+1;
deepfs(A[i][j]);
}
}
}
int lift(int i,int k){
for(int j=0;j<=18;j++){
if(k&(1<<j)){
i=dp[j][i];
}
}
return i;
}
int lca(int a,int b){
if(depth[a]<depth[b]){
b=lift(b,depth[b]-depth[a]);
}
else if(depth[b]<depth[a]){
a=lift(a,depth[a]-depth[b]);
}
if(a==b)return a;
for(int i=18;i>=0;i--){
if(dp[i][a]!=dp[i][b]){
a=dp[i][a];
b=dp[i][b];
}
}
return parent[a];
}
int main(){
ifstream cin("lca.in");
ofstream cout("lca.out");
cin>>n>>m;
for(int i=1;i<n;i++){
cin>>parent[i];
parent[i]--;
A[i].push_back(parent[i]);
A[parent[i]].push_back(i);
}
deepfs(0);
for(int i=0;i<n;i++){
dp[0][i]=parent[i];
}
for(int i=1;i<=18;i++){
for(int j=0;j<n;j++){
dp[i][j]=dp[i-1][dp[i-1][j]];
}
}
while(m--){
int a,b;
cin>>a>>b;
a--;b--;
cout<<lca(a,b)+1<<endl;
}
}