Pagini recente » Cod sursa (job #3163278) | Cod sursa (job #1949428) | Cod sursa (job #2970073) | Cod sursa (job #800595) | Cod sursa (job #3285240)
#include <fstream>
#include <vector>
#define nmax (int)(1e5+1)
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");
int n,q,x,y,rmq[20][nmax],k,a[20][nmax],p[nmax],first[nmax];
vector<int>v[nmax];
void dfs(int nod,int l){
rmq[0][++k]=l;
a[0][k]=nod;
first[nod]=k;
for(auto i:v[nod]){
dfs(i,l+1);
rmq[0][++k]=l;
a[0][k]=nod;
}
}
signed main()
{
cin>>n>>q;
for(int i=2;i<=n;i++){
cin>>x;
v[x].push_back(i);
}
dfs(1,1);
for(int i=1;(1<<i)<=k;i++)
for(int j=1;j<=k;j++){
rmq[i][j]=rmq[i-1][j];
a[i][j]=a[i-1][j];
if(j+(1<<(i-1))<=k&&rmq[i][j]>rmq[i-1][j+(1<<(i-1))]){
rmq[i][j]=rmq[i-1][j+(1<<(i-1))];
a[i][j]=a[i-1][j+(1<<(i-1))];
}
}
for(int i=2;i<=n;i++)
p[i]=p[i/2]+1;
while(q--){
cin>>x>>y;
int st=min(first[x],first[y]),dr=max(first[x],first[y]),e=p[dr-st+1],lca=a[e][st];
if(rmq[e][st]>rmq[e][dr-(1<<e)+1])
lca=a[e][dr-(1<<e)+1];
cout<<lca<<'\n';
}
return 0;
}