#include <bits/stdc++.h>
using namespace std;
std::vector<int> adj[100010], level[100010];
int v[100010], par[100010], Level[100010], t = 0, dis[100010], fin[100010];
void dfs(int s, int l) {
  if (v[s]) return;
  v[s] = 1;
  dis[s] = t++;
  for (int i = 0; i < adj[s].size(); ++i) {
    int t = adj[s][i];
    if (!v[t]) {
      par[t] = s;
      dfs(t, l + 1);
    }
  }
  level[l].push_back(t);
  fin[s] = t++;
  Level[s] = l;
}
int anch[100010][35];
void sparse_table(int n) {
  for (int i = 0; (1 << i) <= n; ++i)
    for (int j = 1; j <= n; ++j) {
      if (!i)
        anch[j][i] = par[j];
      else
        anch[j][i] = anch[anch[j][i - 1]][i - 1];
    }
}
int parent(int x, int p) {
  for (int i = 30; i >= 0; i--) {
    if (p >= (1 << i)) {
      p -= (1 << i);
      x = anch[x][i];
    }
  }
  return x;
}
int main() {
  memset(anch, -1, sizeof anch);
  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    int x;
    cin >> x;
    if (x) adj[x].push_back(i);
  }
  for (int i = 1; i <= n; ++i)
    if (!v[i]) par[i] = -1, dfs(i, 0);
  sparse_table(n);
  int q;
  cin >> q;
  while (q--) {
    int p, x;
    cin >> x >> p;
    if (Level[x] < p or par[x] == -1)
      printf("0 ");
    else {
      int l = Level[x];
      int P = parent(x, p);
      int up = upper_bound(level[l].begin(), level[l].end(), fin[P]) -
               level[l].begin();
      int lo = lower_bound(level[l].begin(), level[l].end(), dis[P]) -
               level[l].begin();
      printf("%d ", up - lo - 1);
    }
  }
}
