#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>
#include <cassert>
#define rep(i,n) for(int i = 0; i < n; ++i )
using namespace std;
using ll = long long;
using P = pair<int,int>;

vector<int> g[200005];
vector<P> p[200005];
int ans[200005];
map<int,int> f(int u=0,int d=0){
  // cout << u << endl;
  map<int,int> s;
  for(int v:g[u]){
    auto t = f(v,d+1);
    if(t.size()>s.size()) swap(s,t);
    for(auto i:t) s[i.first] += i.second;
  }
  s[d]++;
  for(auto i:p[u]) ans[i.first] = s[i.second];
  return s;
}
int main() {
  int n;
  cin >> n;
  rep(i,n-1){
    int p;
    cin >> p;
    g[p-1].push_back(i+1);
  }
  int q;
  cin >> q;
  rep(i,q){
    int u,d;
    cin >> u >> d;
    p[u-1].emplace_back(i,d);
  }
  f();
  rep(i,q) printf("%d\n",ans[i]);
}

#include<iostream>
#include<bits/stdc++.h>
#define int long long int
#define vi vector<int>
#define fo(i,n) for(int i=1;i<=n;i++)
#define foo(i,n) for(int i=0;i<n;i++)
#define sort(v) sort(v.begin(), v.end())
#define rev(v) reverse(v.begin(), v.end())
#define uniq(v) sort(v); v.resize(unique(v.begin(), v.end())-v.begin());
#define ff first
#define ss second
#define pb push_back
#define pii pair<int,int>
#define ok ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
using namespace std;
#define vp vector<pair<int,int>>
#define mod 1000000007
const int huge = 1e17;
               
                
int max(int a,int b){ if(a>b) return a; return b; }
int min(int a,int b){ if(a<b) return a; return b; }
int abbs(int a,int b){   if(a-b < 0) return b-a; return a-b; }
 
 
int lowerB(vi &v, int val){
int ind=v.size(),l=0,r=v.size(),mid;while(l<=r){mid=(l+r)/2;if(v[mid]>=val){ind=mid;r=mid-1;}else l=mid+1;}return ind;
}
 
vi adj[200005]; 
vi in(200005);
vi out(200005);
vi d[200005];
int timer;

void dfs(int node = 1, int dep = 0) {
    in[node] = timer++;
    d[dep].pb(in[node]);
    for(int x: adj[node]) dfs(x, dep+1);
    out[node] = timer++; 
}
 
void solve(){
    int n; cin>>n;
    fo(i,n-1) {
        int x; cin>>x;
        adj[x].pb(i+1);
    }
    dfs();
    int q; cin>>q;
    while(q--) {
        int u, dd;
        cin>>u>>dd;
        int l = in[u], r = out[u];
        int ans = lower_bound(d[dd].begin(), d[dd].end(), l) - lower_bound(d[dd].begin(), d[dd].end(), r+1);
        cout<<ans*-1<<"\n";

    }
    // how many nodes are child of v at depth of d
} 
      
      
signed main(){
   ok
   int t;
   t = 1;
  // cin>>t;
     while(t--){
      solve();
    }
}