Pagini recente » Cod sursa (job #2040252) | Istoria paginii runda/ada36/clasament | Rating Marean Vanghelie (marean) | Cod sursa (job #2469725) | Cod sursa (job #2368488)
#include <stdio.h>
#include <math.h>
#include <iostream>
using namespace std;
struct nod{
int inf;
nod *urm;
}*l[100005];
int i,a,b,k,rmq[200005][20];
int ap[100005];
int x,n,q,h[100005],use[100005];
void adaug(nod *&p,int x){
nod *u;
u=new nod;
u->inf=x;
u->urm=p;
p=u;
return;
}
int kk,st[2*100005];
void df(int x,int height){
nod *p;
use[x]=1;
h[++kk]=height;
st[kk]=x;
if(!ap[x]) ap[x]=kk;
for(p=l[x];p;p=p->urm)
if(!use[p->inf]){ df(p->inf,height+1);
st[++kk]=x;
h[kk]=height;}
}
int j;
int main()
{ freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
int i;
scanf("%d%d",&n,&q);
for(i=2;i<=n;i++) {
scanf("%d",&x);
adaug(l[x],i);
adaug(l[i],x);
}
df(1,0);
n=kk;
//h[1]=0;
//h[++n]=1;
for(i=1;i<=n;i++) rmq[i][0]=i;
for(j=1;(1<<j)<=n;j++)
for(i=1;i<=n-(1<<j)+1;i++){
if(h[rmq[i][j-1]]<h[rmq[i+(1<<(j-1))][j-1]]) rmq[i][j]=rmq[i][j-1];
else rmq[i][j]=rmq[i+(1<<(j-1))][j-1];
}
for(k=1;k<=q;k++){
scanf("%d%d",&a,&b);
a=ap[a];
b=ap[b];
if(a>b) {
int aux=a;
a=b;
b=aux;
}
int log=(int)(log2(b-a+1));
if(h[rmq[a][log]]<h[rmq[b-(1<<log)+1][log]])
printf("%d\n",st[rmq[a][log]]);
else printf("%d\n",st[rmq[b-(1<<log)+1][log]]);
}
return 0;
}