#include <iostream>
#include <vector>
#include <algorithm>

std::vector<std::vector<int>> children, list;
std::vector<int> in, out, depth;
int timer;

void dfs(const int u) {
    in[u] = timer++;
    list[depth[u]].push_back(in[u]);
    for (const int v : children[u]) {
        depth[v] = depth[u] + 1;
        dfs(v);
    }
    out[u] = timer++;
}

int main() {
    int N;
    std::cin >> N;
    children = list = std::vector<std::vector<int>>(N);
    in = out = depth = std::vector<int>(N);
    for (int i = 1; i < N; ++i) {
        int p;
        std::cin >> p;
        children[p - 1].push_back(i);
    }
    dfs(0);
    int Q;
    std::cin >> Q;
    while (Q--) {
        int u, d;
        std::cin >> u >> d;
        u -= 1;
        const auto& v = list[d];
        std::cout << std::lower_bound(v.cbegin(), v.cend(), out[u]) - std::lower_bound(v.cbegin(), v.cend(), in[u]) << '\n';
    }
    return 0;
}

//#pragma GCC optimize("Ofast")
//#pragma GCC target("avx,avx2,fma")
//#pragma GCC optimization("unroll-loops")
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
#define int long long
template<class T> using indexed_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
const int N=2e5+7;
const int mod=1e9+7;
const int INF=1e18+7;
const double EPS=1e-12;
const int dx[]={-1,1,0,0}; // UDLR
const int dy[]={0,0,-1,1}; // UDLR
inline int maximum(int a,int b) {int c=a>b?a:b; return c;}
inline int minimum(int a,int b) {int c=a>b?b:a; return c;}

int n; vector<vector<int>> adj(N); vector<int> dis(N),sub(N),ans(N); map<int, int> *cnt[N];
vector<vector<pair<int,int>>> query(N);
void dfs(int src){
  sub[src]=1;
  for(auto v:adj[src]){
   dis[v]+=dis[src]+1;
   dfs(v);
   sub[src]+=sub[v];
  }
}
void dfsz(int src){
  int mx=-1,big=-1;
  for(auto v:adj[src]){
   dfsz(v);
   if(sub[v]>mx) mx=sub[v],big=v;
  }
  if(big!=-1) cnt[src]=cnt[big];
  else cnt[src]=new map<int,int>();
  (*cnt[src])[dis[src]] ++;
  for(auto v:adj[src]){
    if(v==big) continue;
    for(auto x:*cnt[v]) (*cnt[src])[x.first]+=x.second;
  }
  for(auto p:query[src]){
   ans[p.first]=(*cnt[src])[p.second];
  }
}
int32_t main(){
    cin.tie(nullptr)->sync_with_stdio(false);

    cin>>n;
    for(int i=2;i<=n;i++){
     int x; cin>>x; adj[x].push_back(i);
    }
    dfs(1);
    int q; cin>>q;
    for(int i=0;i<q;i++){
     int u,d; cin>>u>>d;
     query[u].push_back({i,d});
    }
    dfsz(1);
    for(int i=0;i<q;i++) cout<<ans[i]<<'\n';

 return 0;
}
