#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > g;
const int N = 1e5 + 5;
int n, p[N], tim = 1, in[N], out[N], lvl[N], sparse[N][20];
vector<pair<int, int> > group[N];
void dfs(int node) {
  in[node] = tim++;
  lvl[node] = lvl[p[node]] + 1;
  group[lvl[node]].push_back(make_pair(in[node], node));
  for (int i = 0; i < g[node].size(); i++) dfs(g[node][i]);
  out[node] = tim++;
}
void build() {
  for (int i = 1; i <= 18; i++) {
    for (int j = 1; j <= n; j++) {
      if (sparse[j][i - 1] != -1)
        sparse[j][i] = sparse[sparse[j][i - 1]][i - 1];
    }
  }
}
int solve(int v, int p) {
  int pthparent = v;
  for (int i = 0; i <= 18; i++) {
    if (p & (1 << i)) {
      pthparent = sparse[pthparent][i];
    }
    if (pthparent <= 0) return 0;
  }
  int tin = in[pthparent], tout = out[pthparent];
  int last = lower_bound(group[lvl[v]].begin(), group[lvl[v]].end(),
                         make_pair(tout, 0)) -
             group[lvl[v]].begin();
  int first = lower_bound(group[lvl[v]].begin(), group[lvl[v]].end(),
                          make_pair(tin, 0)) -
              group[lvl[v]].begin();
  return last - first - 1;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  memset(sparse, -1, sizeof sparse);
  cin >> n;
  g.resize(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> p[i];
    sparse[i][0] = p[i];
    g[p[i]].push_back(i);
  }
  dfs(0);
  build();
  int q;
  cin >> q;
  while (q--) {
    int v, p;
    cin >> v >> p;
    cout << solve(v, p) << ' ';
  }
  return 0;
}
