/**
* Author: Sergey Kopeliovich (Burunduk30@gmail.com)
* Date: 2015.02.16
*/
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < (int)(n); i++)
const int N = 1e5;
const int K = 17; // ceil(log_2(N+1))
int p[N][K];
vector<int> c[N]; // graph
int T, t_in[N], t_out[N], dep[N];
void dfs( int v, int d = 0 ) {
t_in[v] = T++;
dep[v] = d;
for (int x : c[v])
dfs(x, d + 1);
t_out[v] = T++;
}
int is_ancestor( int a, int b ) {
return t_in[a] <= t_in[b] && t_out[b] <= t_out[a];
}
int lca( int a, int b ) {
for (int k = K - 1; k >= 0; k--)
if (!is_ancestor(p[a][k], b))
a = p[a][k];
return is_ancestor(a, b) ? a : p[a][0];
}
inline int readChar() {
int c = getchar();
while (c <= 32)
c = getchar();
return c;
}
inline int readInt() {
int s = 0, c = readChar(), x = 0;
if (c == '-')
s = 1, c = getchar();
while ('0' <= c && c <= '9')
x = x * 10 + c - '0', c = getchar();
return s ? -x : x;
}
template <class T> inline void writeInt( T x ) {
if (x < 0)
putchar('-'), x = -x;
char s[24];
int n = 0;
while (x || !n)
s[n++] = '0' + x % 10, x /= 10;
while (n--)
putchar(s[n]);
}
int main() {
int n = readInt();
p[0][0] = 0; // root = 0
for (int i = 1; i < n; i++) {
p[i][0] = readInt() - 1;
c[p[i][0]].push_back(i);
}
dfs(0);
for (int k = 1; k < K; k++)
forn(i, n)
p[i][k] = p[p[i][k-1]][k-1];
int k = readInt();
while (k--) {
writeInt(lca(readInt() - 1, readInt() - 1) + 1);
putchar('\n');
}
return 0;
}