#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 40009, M = 80009;
int n, m;
int h[N], e[M], ne[M], tot;
int mk[N], p[N], ans[M];
struct ver{
int y, id, v;
};
vector<ver> query[N];
void add(int a, int b) {
e[++ tot] = b; ne[tot] = h[a]; h[a] = tot;
}
int find(int x) {
return x == p[x] ? x : p[x] = find(p[x]);
}
void tarjan(int x) {
mk[x] = 1;
for(int i = h[x]; i; i = ne[i]) {
int j = e[i];
if(mk[j]) continue;
tarjan(j);
p[j] = x;
}
mk[x] = 2;
for(ver item : query[x]) {
int y = item.y, id = item.id, v = item.v;
if(mk[y] == 2)
if(x == find(y)) ans[id] = v;
}
}
int main() {
cin >> n;
int root;
for(int i = 0; i < n; i ++) {
int a, b;
scanf("%d%d", &a, &b);
if(b == -1) root = a, p[a] = a;
else add(a, b), add(b, a), p[a] = a, p[b] = b;
}
cin >> m;
for(int i = 0; i < m; i ++) {
int a, b;
scanf("%d%d", &a, &b);
query[a].push_back({b, i, 1});
query[b].push_back({a, i, 2});
}
tarjan(root);
for(int i = 0; i < m; i ++ )
printf("%d\n", ans[i]);
return 0;
}