void Build(int x,int f)
{
fa[x][0] = f,dep[x] = dep[f] + 1;
int y = f,i = 1;
while (y > 0)
{
fa[x][i] = fa[y][i - 1],
y = fa[y][i - 1];
i ++;
}
fm(tmp,x)
if (e[tmp].to != f)
Build(e[tmp].to,x);
}
int Lca(int x,int y)
{
if (dep[x] > dep[y]) swap(x,y);
int i = 0;
for (int dis = dep[y] - dep[x];dis;dis >>= 1,i ++)
if ((dis & 1) == 1) y = fa[y][i];
if (x == y) return x;
i = 0;
while (fa[x][i] != fa[y][i]) i ++;
i --;
while (i >= 0)
{
while (i >= 0 && fa[x][i] == fa[y][i]) i --;
if (i >= 0)
x = fa[x][i],y = fa[y][i];
}
return fa[x][0];
}
const
maxn=40000;
maxm=40000;
var
root:longint;
i,j,k,n,m,x,y,t:longint;
deep:array[0..maxn] of longint;
f:array[0..maxn,0..20] of longint;
head:array[0..maxn*2,1..2] of longint;
next:array[0..maxn*2,1..2] of longint;
procedurebuild(x,fa,d:longint);var
k,y,i:longint;
begin
f[x,0]:=fa;
deep[x]:=d;
y:=fa;i:=1;
while y>0dobegin
f[x,i]:=f[y,i-1];
y:=f[y,i-1];
inc(i);
end;
k:=head[x,1];
while k>0dobeginif next[k,1]=fa thenbegin
k:=next[k,2];
continue;
end;
build(next[k,1],x,d+1);
k:=next[k,2];
end;
end;
functionlca(l,r:longint):longint;
var
x,y,t,jump,i:longint;
p:boolean;
begin
x:=l;y:=r;
if deep[x]>deep[y] thenbegin
t:=x;
x:=y;
y:=t;
end;
jump:=deep[y]-deep[x];
i:=0;
while jump>0dobeginif jump and1>0then y:=f[y,i];
inc(i);
jump:=jump shr1;
end;
if(x=y)thenexit(x);
i:=0;
while(f[x,i]<>f[y,i])do inc(i); dec(i);
while(i>=0)dobeginwhile (i>=0) and (f[x,i]=f[y,i]) do dec(i);
if i<0thenbreak;
x:=f[x,i];y:=f[y,i];
end;
exit(f[x,0]);
end;
begin
readln(n);
for i:=1to n dobegin
readln(x,y);
if(y>0)thenbegin
inc(t);
if head[x,1]=0then head[x,1]:=t;
next[t,1]:=y;
next[t,2]:=0;
next[head[x,2],2]:=t;
head[x,2]:=t;
inc(t);
if head[y,1]=0then head[y,1]:=t;
next[t,1]:=x;
next[t,2]:=0;
next[head[y,2],2]:=t;
head[y,2]:=t;
endelse
root:=x;
end;
build(root,0,0);
readln(m);
for i:=1to m dobegin
readln(x,y);
if(lca(x,y)=x)then writeln('1')
elseif(lca(x,y)=y)then writeln('2')
else writeln('0')
end;
end.