    #include <bits/stdc++.h>
    using namespace std;
    #include <math.h>
    #include <iomanip>
    #include <cstdint>
    #include <string>
    #include <sstream>
    template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
    template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
    #define rep(i,n) for (int i = 0; i < (n); ++i)
    typedef long long ll;
    using P=pair<ll,ll>;
    const int INF=1001001001;
    const int mod=998244353;
    
    vector<int>G[200005],r[200005];
    int in[200005],out[200005],depth[200005];
    int id;

    void dfs(int i,int d=0){
      in[i]=id++;
      depth[i]=d;
      for(int u:G[i]){dfs(u,d+1);}
      out[i]=id;
    }

    void solve(){
      int n;
      cin>>n;
      rep(i,n-1){
        int p;
        cin>>p;
        p--;
        G[p].push_back(i+1);
      }
      dfs(0);
      rep(i,n){r[depth[i]].push_back(in[i]);}
      rep(i,n){sort(r[i].begin(),r[i].end());}
      int Q;
      cin>>Q;
      rep(i,Q){
        int u,d;
        cin>>u>>d;
        u--;
        int ans=lower_bound(r[d].begin(),r[d].end(),out[u])-lower_bound(r[d].begin(),r[d].end(),in[u]);
        cout<<ans<<endl;
      }
    }
    int main(){
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      solve();
      return 0;
    }
#include <bits/stdc++.h>

using namespace std;

const int O = 2e5 + 1;

vector <int> c, dp, g[O], Max;

int t = 1;

bool how_sort(int x, int y){
    return Max[x] < Max[y];
}

int dfs(int u, int par = 0){
    Max[u] = 0;
    for (int v : g[u]){
        if (v == par) continue;
        dp[v] = dp[u] + 1;
        Max[u] = max(Max[u], dfs(v, u) + 1);
    }
    return Max[u];
}

void dfs1(int u, int par = 0){
    c[u] = t;
    for (int v : g[u]){
        if (v == par) continue;
        t += 1;
        dfs1(v, u);
        t += 1;
    }
}

main(){
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int n; cin >> n;
    c.resize(n + 1);
    dp.resize(n + 1);
    Max.resize(n + 1);
    for (int i = 1; i < n; ++ i){
        int u, v; cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1);
    int compare = 0;
    int root = 1;
    for (int i = 1; i <= n; ++ i){
        if (dp[i] > compare){
            compare = dp[i];
            root = i;
        }
    }
    dfs(root);
    for (int i = 1; i <= n; ++ i){
        sort(g[i].begin(), g[i].end(), how_sort);
    }
    dfs1(root);
    for (int i = 1; i <= n; ++ i) cout << c[i] << " ";
}
/***
10
1 2
2 3
2 4
4 5
5 6
6 7
6 8
8 10
8 9
**/
