#include<bits/stdc++.h>
#define fast {ios_base::sync_with_stdio(false);cin.tie(NULL);}
#define all(x) (x).begin(), (x).end()
#define Unique(a)       a.erase(unique(all(a)), a.end())
#define ld long double
#define pb push_back
#define fi first
#define se second
#define inf 1e9
using namespace std;	
typedef long long int ll;

const int mxn=2e5+5,mod=1e9+7;
int a[mxn],dis[mxn];
vector<int>g[mxn];
bool vis[mxn];

int timer;
vector<int> tin(mxn), tout(mxn);
vector<vector<int>> up;

vector<int>lev[mxn];

void dfs(int v, int p)
{
    tin[v] = ++timer;
    lev[dis[v]].pb(timer);

    for (int u : g[v]) {
        if (u != p){
        	dis[u]=dis[v]+1;	
            dfs(u, v);
        }
    }
    tout[v] = ++timer;
}

int ask(int d,int x){
	int res=-1;
	for(int i=17;i>=0;--i){
		int sum=res+(1<<i);
		if(sum>=lev[d].size()) continue;
		if(lev[d][sum]<=x)res=sum;
	}
	return res;
}

int main(void){
	fast;
	int n,i,q,x;
	cin>>n;
	for(i=2;i<=n;i++){

		cin>>x;
		g[x].pb(i);
		g[i].pb(x);
		
	}
	dis[1]=0;
	
	dfs(1,0);
	
	cin>>q;
	
	while(q--){

		int x,y,l1=0,l2=0;
		cin>>x>>y;
		int l=tin[x];
		int r=tout[x];
		cout<<ask(y,r)-ask(y,l-1)<<'\n';
	}
}

#include <bits/stdc++.h>
using namespace std;
const int N=2e5+2;
int n,q,f[N];
int cnt,hd[N],to[N],nxt[N];
int hd1[N],d[N],nxt1[N],ans[N];
void adde(int x,int y)
{
	nxt[++cnt]=hd[x];
	to[hd[x]=cnt]=y;
}
void dfs(int x,int dep)
{
	for(int i=hd1[x];i;i=nxt1[i])
		ans[i]=-f[d[i]];
	++f[dep];
	for(int i=hd[x];i;i=nxt[i])
		dfs(to[i],dep+1);
	for(int i=hd1[x];i;i=nxt1[i])
		ans[i]+=f[d[i]];
}
int main()
{
	scanf("%d",&n);
	for(int i=2,x;i<=n;++i)
	{
		scanf("%d",&x);
		adde(x,i);
	}
	scanf("%d",&q);
	for(int i=1,x,y;i<=q;++i)
	{
		scanf("%d%d",&x,&y);
		nxt1[i]=hd1[x];
		d[hd1[x]=i]=y;
	}
	dfs(1,0);
	for(int i=1;i<=q;++i)
		printf("%d\n",ans[i]);
}