#include <bits/stdc++.h>
#define ar array

using namespace std;

const int mxN = 2e5;
vector<int> kids[mxN], starts[mxN], inTs[mxN];
int inT[mxN], outT[mxN];

void dfs(int &T, int cur, int d) {
  inTs[d].push_back(T);
  inT[cur] = T++;
  for (int nxt : kids[cur])
    dfs(T, nxt, d+1);
  outT[cur] = T++;
}

int main() {
  cin.tie(0)->sync_with_stdio(0);

  int n; cin >> n;
  for (int i = 1; i < n; ++i) {
    int j; cin >> j; --j;
    kids[j].push_back(i);
  }

  { int T = 0; dfs(T, 0, 0); }

  int q; cin >> q;

  for (int qq = 0; qq < q; ++qq) {
    int i, d; cin >> i >> d; --i;

    auto lo = lower_bound(inTs[d].begin(), inTs[d].end(), inT[i]);
    auto hi = upper_bound(inTs[d].begin(), inTs[d].end(), outT[i]);

    cout << hi-lo << '\n';
  }

}

#include <cstdio>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
const int M = 200005;
#define pii pair<int,int>
#define make make_pair
int read()
{
	int x=0,f=1;char c;
	while((c=getchar())<'0' || c>'9') {if(c=='-') f=-1;}
	while(c>='0' && c<='9') {x=(x<<3)+(x<<1)+(c^48);c=getchar();}
	return x*f;
}
int n,m,tot,f[M],dep[M],ans[M];map<int,int> mp[M];
struct edge
{
    int v,next;
}e[2*M];vector<pii> v[M];
void dfs(int u,int fa)
{
    dep[u]=dep[fa]+1;
    mp[u][dep[u]-1]=1;
    for(int i=f[u];i;i=e[i].next)
    {
        int v=e[i].v;
        if(v==fa) continue;
        dfs(v,u);
        if(mp[u].size()<=mp[v].size()) swap(mp[u],mp[v]);
        map<int,int>::iterator it=mp[v].begin();
        for(;it!=mp[v].end();it++)
            mp[u][(*it).first]+=(*it).second;
    }
    for(int i=0;i<v[u].size();i++)
        ans[v[u][i].second]=mp[u][v[u][i].first];
}
signed main()
{
    n=read();
    for(int i=2;i<=n;i++)
    {
        int j=read();
        e[++tot]=edge{i,f[j]},f[j]=tot;
        e[++tot]=edge{j,f[i]},f[i]=tot;
    }
    m=read();
    for(int i=1;i<=m;i++)
    {
        int u=read(),d=read();
        v[u].push_back(make(d,i));
    }
    dfs(1,0);
    for(int i=1;i<=m;i++)
        printf("%d\n",ans[i]);
}
