#include <bits/stdc++.h>
using namespace std;
///dfs, aint
ifstream f("lca.in");
ofstream g("lca.out");
const int nmax = 1000;
int v[nmax + 5], prima_poz[nmax + 5];
int n;
vector <int> a[nmax + 5];
struct structura{
int adancime, nod;
};
structura Euler[2 * nmax + 5], aint[4 * nmax + 5];
int nr_elemente;
void euler(int k, int depth)
{
++nr_elemente;
Euler[nr_elemente].adancime = depth;
Euler[nr_elemente].nod = k;
if(prima_poz[k] == 0)
prima_poz[k] = nr_elemente;
for(auto i : a[k])
{
euler(i, depth + 1);
++nr_elemente;
Euler[nr_elemente].adancime = depth;
Euler[nr_elemente].nod = k;
}
}
void build(int nod, int l, int r)
{
if(l != r)
{
int m=(l + r)/2;
build(2*nod, l, m);
build(2*nod + 1, m + 1, r);
if(aint[2 * nod].adancime > aint[2 * nod + 1].adancime)
{
aint[nod].adancime = aint[2 * nod + 1].adancime;
aint[nod].nod = aint[2 * nod + 1].nod;
}
else
{
aint[nod].adancime = aint[2 * nod].adancime;
aint[nod].nod = aint[2 * nod].nod;
}
}
else
{
///l = r
aint[nod].adancime = Euler[l].adancime;
aint[nod].nod = Euler[l].nod;
}
}
structura mini(structura a, structura b)
{
if(a.adancime < b.adancime)
return a;
else
return b;
}
structura q(int nod, int l, int r, int ql, int qr)
{
if(l > qr || r < ql || r < l)
{
return {nmax, -1};
}
else
{
if( ql <= l && ql <= r && qr >= l && qr >= r)
{
///int [l, r] este inclus in [ql, qr]
return aint[nod];
}
else
{
int m = (l + r)/2;
return mini(q(2*nod, l, m, ql, qr), q(2*nod + 1, m + 1, r, ql, qr));
}
}
}
int main()
{
int Q, i, x, y;
f >> n >> Q;
for(i = 1; i <= n - 1; ++i)
{
f >> x;
a[x].push_back(i + 1);
}
euler(1, 0);
build(1, 1, nr_elemente);
for(i = 1; i <= Q; ++i)
{
f >> x >> y;
if(prima_poz[x] < prima_poz[y])
g << q(1, 1, nr_elemente, prima_poz[x], prima_poz[y]).nod << "\n";
else
g << q(1, 1, nr_elemente, prima_poz[y], prima_poz[x]).nod << "\n";
}
return 0;
}