#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;constint MOD =998244353;constint N =2e5+10;int n, m, s, a, b;
vector<int>e[N];int dep[N], fa[N][20];//深度//第u个节点向上走2的i次方之后所对应的祖先voiddfs(int u,int father){
dep[u]= dep[father]+1;
fa[u][0]= father;//初始化递归的第一项for(int i =1; i <=19; i ++){
fa[u][i]= fa[fa[u][i -1]][i -1];}for(int v : e[u]){if(v != father)dfs(v, u);}}intlca(int u,int v){if(dep[u]< dep[v])swap(u, v);//先跳到同一层for(int i =19; i >=0; i --){if(dep[fa[u][i]]>= dep[v]){
u = fa[u][i];}//一步一步的跳}if(u == v)return v;for(int i =19; i >=0; i --){if(fa[u][i]!= fa[v][i]){
u = fa[u][i], v = fa[v][i];}}return fa[u][0];}intmain(){
cin >> n;while(n --){
cin >> a >> b;if(b ==-1) s = a;else{
e[a].push_back(b);
e[b].push_back(a);}}dfs(s,0);
cin >> m;while(m --){
cin >> a >> b;int o =lca(a, b);if(o == a) cout <<1<< endl;elseif(o == b) cout <<2<< endl;else cout <<0<< endl;}return0;}