#include <bits/stdc++.h>
using namespace std;
int n, k, i, j, x, a, m, L[400000], R[400000], lavel;
vector<int> root, g[200005], s[200005];
int in[400000], timer, d[400000];
int p[20][100005], depth[100005];
void dfs(int v) {
  int i;
  L[v] = timer;
  in[v] = timer++;
  d[in[v]] = depth[v];
  for (i = 1; i < 20; i++) p[i][v] = p[i - 1][p[i - 1][v]];
  for (i = 0; i < g[v].size(); i++) {
    if (p[0][v] == g[v][i]) continue;
    depth[g[v][i]] = depth[v] + 1;
    p[0][g[v][i]] = v;
    dfs(g[v][i]);
  }
  R[v] = timer++;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> a;
    a--;
    if (a != -1)
      g[a].push_back(i);
    else
      root.push_back(i);
  }
  for (i = 0; i < root.size(); i++) dfs(root[i]);
  for (i = 0; i < timer; i++) s[d[i]].push_back(i);
  for (i = 0; i < timer; i++) sort(s[i].begin(), s[i].end());
  cin >> m;
  while (m--) {
    cin >> a >> lavel;
    a--;
    if (depth[a] < lavel) {
      cout << 0 << " ";
      continue;
    }
    x = depth[a];
    for (i = 19; i >= 0; i--) {
      if (lavel >= (1 << i)) {
        a = p[i][a];
        lavel -= (1 << i);
      }
    }
    cout << (upper_bound(s[x].begin(), s[x].end(), R[a]) -
             lower_bound(s[x].begin(), s[x].end(), L[a])) -
                1
         << " ";
  }
  return 0;
}
