#include <iostream>
#include <algorithm>
#include <unordered_set>
#include <set>
#include <vector>
#include <queue>
#include <map>
#include <numeric>
#include <math.h>
#include <complex>

using namespace std;

#define rep(i, n) for (long long int i = 0; i < (long long int)(n); i++)
#define irep(i, n) for (long long int i = 1; i <= (long long int)(n); i++)
#define drep(i, n, diff) for (long long int i = 0; i < (long long int)(n); i += diff)
#define mod 1000000007
#define INF 100100100100100101
#define ld(val) printf("%s : %lld\n", #val, val);
#define sd(val) printf("%s : %s\n", #val, val.c_str());

typedef long long int ll;
typedef pair<ll, ll> P;
typedef pair<P, P> PP;
typedef tuple<ll, ll, ll> TP;

vector<ll> to[200005];
vector<ll> lst[200005];
ll d[200005];
ll in[200005];
ll out[200005];
ll cnt;

void dfs(ll n, ll cd) {
  in[n] = cnt;
  cnt++;
  lst[cd].push_back(in[n]);
  for(auto v: to[n]) {
    dfs(v, cd+1);
  }
  out[n] = cnt;
}

int main() {
  ll n;
  cin >> n;
  rep(i, n-1) {
    ll x;
    cin >> x;
    to[x-1].push_back(i+1);
  }
  
  dfs(0, 0);

  ll q;
  cin >> q;
  rep(i, q) {
    ll u, d;
    cin >> u >> d;
    --u;
    ll l = lower_bound(lst[d].begin(), lst[d].end(), out[u]) - lst[d].begin();
    ll r = lower_bound(lst[d].begin(), lst[d].end(), in[u]) - lst[d].begin();
    printf("%lld\n", l-r);
  }
 
  return 0;
}
#include <bits/stdc++.h>
#define int long long

using namespace std;
const int MOD=1e9+7;

typedef pair<pair<int,int>,pair<int,int>> pii;

const int N = 200005;
int n,q,root=1,dis[N];
vector<int> G[N];
vector<pii> Ques;
int L[N],R[N],TIME=0;

int calc_QUAI(int x){
	return x/sqrt(n);
}

bool cmp(pii a, pii b){
	if(calc_QUAI(a.first.first)!=calc_QUAI(b.first.first))
		return calc_QUAI(a.first.first)<calc_QUAI(b.first.first);
	return a.first.second<b.first.second;
}

void dfs(int now,int dep){
	L[now]=TIME++;
	dis[L[now]]=dep;
	for(int next:G[now])
		dfs(next,dep+1);
	R[now]=TIME-1;
}

int32_t main(){
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);	cout.tie(nullptr);

	cin >> n;
	for(int i=1;i<n;++i){
		int p;	cin >> p;
		G[p].push_back(i+1);
	}


	dfs(root,0);

	cin >> q; Ques.resize(q);
	for(int i=0;i<q;++i){
		int u,d;	cin >> u >> d;
		Ques[i]={{L[u],R[u]},{d,i}};
	}

	sort(Ques.begin(),Ques.end(),cmp);

	int LL=0,RR=0;
	vector<int> COUNT;	COUNT.resize(n);
	vector<int> ans;	ans.resize(q);
	COUNT[dis[L[0]]]++;
	for(int i=0;i<q;++i){
		while(RR<Ques[i].first.second){
			++RR;
			COUNT[dis[RR]]++;
		}
		while(RR>Ques[i].first.second){
			COUNT[dis[RR]]--;
			--RR;
		}
		while(LL<Ques[i].first.first){
			COUNT[dis[LL]]--;
			++LL;
		}
		while(LL>Ques[i].first.first){
			--LL;
			COUNT[dis[LL]]++;
		}
		ans[Ques[i].second.second]=COUNT[Ques[i].second.first];
	}
	for(int i=0;i<q;++i)	cout << ans[i] << '\n';

	return 0;
}