Pagini recente » Cod sursa (job #395341) | Cod sursa (job #600084) | Cod sursa (job #1982841) | Cod sursa (job #3244187) | Cod sursa (job #1575841)
#include<cstdio>
int a[100001][21],i,j,n,m,k,x,y,h[1000001];
int main ()
{
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
scanf("%d%d",&n,&m);
for(i=2;i<=n;i++)
{
scanf("%d",&k);
a[i][0]=k;
h[i]=h[k]+1;
}
for(i=1;i<=n;i++)
for(j=1;j<=20;j++)
a[i][j]=a[a[i][j-1]][j-1];
for(i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
if(h[x]>h[y])
{
int q=h[x]-h[y],p=1;
while(q!=0)
{
p=1;
int qq=0;
while(p*2<=q)
{
p*=2;
qq++;
}
x=a[x][qq];
q-=p;
}
}
else
{
int q=h[y]-h[x],p=1;
while(q!=0)
{
p=1;
int qq=0;
while(p*2<=q)
{
p*=2;
qq++;
}
y=a[y][qq];
q-=p;
}
}
if(x==y)
printf("%d\n",x);
else
{
int p=1;
for(j=1;j<=20;j++)
if(p*2>h[x])
break;
else
p*=2;
int o=0;
while(j!=-1)
{
if(a[x][j-1]!=a[y][j-1])
{
x=a[x][j-1];
y=a[y][j-1];
}
else
o=j;
j--;
}
if(a[x][o]!=a[y][o])
printf("1\n");
else
printf("%d\n",a[x][o]);
}
}
}