#include<bits/stdc++.h>
using namespace std;

vector<vector<int>> tree, depths;
vector<pair<int,int>> times;
int t = 0;

void dfs(int root, int depth) {
	times[root].first = t;
  	depths[depth].push_back(t++);
  
  	for (auto v: tree[root]) {
    	dfs(v, depth + 1);
    }
  
  	times[root].second = t++;
}

int main() {
  	ios::sync_with_stdio(false);
  	cin.tie(0);
  
 	int n; cin >> n;
  	tree.resize(n);
  	depths.resize(n);
  	times.resize(n);
  	fill(times.begin(), times.end(), make_pair(0,0));
  
  	for (int i = 1; i < n; i++) {
    	int u; cin >> u; u--;
      	tree[u].push_back(i);
    }
  
  	dfs(0, 0);
  	
  	int q; cin >> q;
  	while (q--) {
    	int u,d; cin >> u >> d; u--;
      	int l = lower_bound(depths[d].begin(), depths[d].end(), times[u].first) - depths[d].begin();
      	int r = upper_bound(depths[d].begin(), depths[d].end(), times[u].second) - depths[d].begin() - 1;
      
      	int ans = max(0, r - l + 1);
      	cout << ans << '\n';
    }
}
#include<bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define vll vector<int>
#define pii pair<int,int>
#define pb push_back
#define sz(v) (int)(v).size()
#define inf 1e18
#define md 1000000007
#define all(v) (v).begin(),(v).end()
#define rep(i,a,b) for(int i=a;i<b;++i)
using namespace std;

const int M = 2e5 + 10;

vll g[M];
int n,t,m;
int sz[M],son[M],h[M];
void run(int u,int pa=0){
	sz[u]=1;
	for(auto v:g[u])if(v!=pa){
		h[v]=h[u]+1;
		run(v,u),sz[u]+=sz[v];
		if(sz[v]>sz[son[u]])son[u]=v;
	}
}
int ans[M],sum;
int mx,ch;
vector<pii> q[M];
int cnt[M];

void up(int u,int pa,int y){
	// add
	cnt[h[u]]+=y?1:-1;
	for(auto v:g[u])if(v!=pa and v!=ch) up(v,u,y);
}
void dfs(int u,int pa=0,bool ok=1){
	for(auto v:g[u])if(v!=pa and v!=son[u]) dfs(v,u);
	if(son[u]) dfs(son[u],u,0),ch=son[u];
	up(u,pa,1),ch=0;
	// cal answer
	for(auto p:q[u]) {
		if(p.fi<h[u]) continue;
		ans[p.se]=cnt[p.fi];
	}
	if(ok) up(u,pa,0);
}
int32_t main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
   	
   	cin>>n;
   	rep(i,2,n+1){
   		int p;
   		cin>>p;
   		g[p].pb(i);
   	}
   	run(1);
   	int t;
   	cin>>t;
   	rep(i,0,t) {
   		int u,d;
   		cin>>u>>d;
   		q[u].pb({d,i});
   	}
   	dfs(1);
   	rep(i,0,t) cout<<ans[i]<<"\n";
   	
    
    return 0;
}