Pagini recente » Cod sursa (job #2901096) | Cod sursa (job #2180069) | Cod sursa (job #740090) | Cod sursa (job #660764) | Cod sursa (job #553756)
Cod sursa(job #553756)
#include<cstdio>
const int N=1002;
int n,m;
short int pred[N][N];
void citire()
{
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
scanf("%d%d",&n,&m);
for (int i=2;i<=n;++i)
scanf("%hd",&pred[i][++pred[i][0]]);
}
void predecesori()
{
int cur;
for (int i=2;i<=n;++i)
{
cur=pred[pred[i][1]][1];
while (cur!=0)
{
pred[i][++pred[i][0]]=cur;
cur=pred[pred[i][pred[i][0]]][1];
}
}
}
bool gasit(int x,short int a[])
{
for (int i=1;i<=a[0];++i)
if (a[i]==x)
return true;
return false;
}
int rez(int x,int y)
{
if (x==y)
return x;
if (gasit(x,pred[y]))
return x;
if (gasit(y,pred[x]))
return y;
int nr1=pred[x][0],nr2=pred[y][0];
while (pred[x][nr1]==pred[y][nr2] && nr1>0 && nr2>0)
--nr1,--nr2;
return pred[x][nr1+1];
}
int main()
{
citire();
predecesori();
int x,y;
for (int i=1;i<=m;++i)
{
scanf("%d%d",&x,&y);
printf("%d\n",rez(x,y));
}
return 0;
}