Cod sursa(job #711668)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
#define dim 100005
#define logn 23
int stramos[dim][logn], t[dim];
int n, m, i;
inline bool cmp(int a , int b)
{
return a>b;
}
void read()
{
fin>> n >>m;
t[1]=-1;
for(i=2;i<=n;++i)
{
int par,grad=0;
fin>>par;
t[i]=par;
stramos[i][++grad]=i;
while(par!=-1)
{
++grad;
stramos[i][grad]=par;
par=t[par];
}
stramos[i][0]=grad;
}
}
void solve()
{
int a, b;
stramos[1][0]=1;
stramos[1][1]=1;
for(i=1;i<=m;++i)
{
fin>>a >>b;
int ok=1,j,k;
if(a>b)
swap(a,b);
for(j=1;;++j)
{
for(k=1;stramos[a][j]<=stramos[b][k];++k)
if(stramos[a][j]==stramos[b][k])
{
ok=0;
break;
}
if(ok==0)
break;
}
fout<<stramos[a][j] <<'\n';
}
}
int main()
{
read();
solve();
return 0;
}