#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--)
#define rrep(i,n) RREP(i,(n)-1,0)
#define all(v) v.begin(), v.end()
#define endk '\n'
const int inf = 1e9+7;
const ll longinf = 1LL<<60;
const ll mod = 1e9+7;
const ll mod2 = 998244353;
const ld eps = 1e-10;
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b){if(a>b) a=b;}
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b){if(a<b) a=b;}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int n; cin >> n;
  vector<int> P(n, -1);
  vector<vector<int>> G(n);
  REP(i, 1, n) {
    cin >> P[i];
    P[i]--;
    G[P[i]].push_back(i);
  }
  vector<int> in(n), out(n);
  vector<vector<int>> D(n);
  int tmp = 0;
  auto dfs = [&](auto dfs, int cur, int depth) -> void {
    in[cur] = tmp++;
    D[depth].push_back(in[cur]);
    for(int ne: G[cur]) {
      dfs(dfs, ne, depth+1);
    }
    out[cur] = tmp++;
    D[depth].push_back(out[cur]);
  };
  dfs(dfs, 0, 0);
  int q; cin >> q;
  rep(i, q) {
    int u, d; cin >> u >> d;
    u--;
    cout << (upper_bound(all(D[d]), out[u]) - lower_bound(all(D[d]), in[u])) / 2 << endk;
  }
  return 0;
}

#include<bits/stdc++.h>
using namespace std;
int b[200005];
int main()
{
	int N,min=0;
	cin>>N;
	for(int i=1;i<=N;i++)
	{
		int n;
		scanf("%d",&n);
		b[n]++;
		
		if(n==min)
		{
			for(int j=n;;j++)
			{
				if(b[j]==0)
				{
					min=j;
					break;
				}
			}
		}
		printf("%d\n",min);
	}
	

}