// LCA (最近公共祖先)算法
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 4e4 + 10, M = 2 * N;
int root;
int h[N], e[M], ne[M], idx;
int depth[N], fa[N][16];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a]; h[a] = idx ++;
}
//宽度优先搜索 预处理depth和fa数组
void bfs(int root)
{
memset(depth, 0x3f, sizeof depth);
int q[N], hh = 0, tt = -1;
depth[root] = 1, depth[0] = 0;
q[++ tt] = root;
while (hh <= tt)
{
int t = q[hh ++];
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (depth[j] > depth[t] + 1)
{
depth[j] = depth[t] + 1;
q[++ tt] = j;
fa[j][0] = t;
for (int i = 1; i <= 15; i ++)
fa[j][i] = fa[fa[j][i - 1]][i - 1];
}
}
}
}
int lca(int a, int b)
{
if (depth[a] < depth[b]) swap(a, b);
for (int k = 15; k >= 0; k --)
if (depth[fa[a][k]] >= depth[b])
a = fa[a][k];
if (a == b) return a;
for (int k = 15; k >= 0; k --)
if (fa[a][k] != fa[b][k])
{
a = fa[a][k];
b = fa[b][k];
}
return fa[a][0];
}
int main(void)
{
int n, m;
cin >> n;
memset(h, -1, sizeof h);
for (int i = 0; i < n; i ++)
{
int a, b;
cin >> a >> b;
if (b == -1) root = a;
else add(a, b), add(b, a);
}
bfs(root);
cin >> m;
for (int i = 0; i < m; i ++)
{
int a, b;
cin >> a >> b;
int p = lca(a, b);
if (p == a) cout << "1" << endl;//x是y的祖先
else if (p == b) cout << "2" << endl;//y是x的祖先
else cout << "0" << endl;
}
return 0;
}