#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 40010,M = 2 * N;
int h[N],e[M],ne[M],idx;
int fa[N],son[N],d[N],sz[N];
int top[N];
int n,m;
void dfs1(int x,int fath){
fa[x] = fath;
d[x] = d[fath] + 1;
sz[x] = 1;
for(int i = h[x];~i;i = ne[i]){
int j = e[i];
if(j == fath) continue;
dfs1(j,x);
sz[x] += sz[j];
if(sz[j] > sz[son[x]]) son[x] = j;
}
}
void dfs2(int x,int topx){
top[x] = topx;
if(son[x]) dfs2(son[x],topx);
for(int i = h[x];~i;i = ne[i]){
int j = e[i];
if(j == son[x] || j == fa[x]) continue;
dfs2(j,j);
}
}
int lca(int x,int y){
while(top[x] != top[y]){
if(d[top[x]] < d[top[y]]) swap(x,y);
x = fa[top[x]];
}
return d[x] < d[y] ? x : y;
}
void add(int a,int b){
e[idx] = b,ne[idx] = h[a],h[a] = idx ++;
}
int main(){
cin >> n;
int root = 0;
memset(h,-1,sizeof h);
for(int i = 1;i <= n;i ++){
int a,b;
cin >> a >> b;
if(b == -1){
root = a;
continue;
}
add(a,b),add(b,a);
}
dfs1(root,0);
dfs2(root,root);
cin >> m;
for(int i = 1;i <= m;i ++){
int a,b;
cin >> a >> b;
int c = lca(a,b);
if(a == c){
cout << 1 << endl;
}
else if(b == c){
cout << 2 << endl;
}
else
cout << 0 << endl;
}
return 0;
}
OrzOrzOrz
srosro