#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 4, B = 17;
vector<int> ed[N], pts, pin[N];
int n, m, par[B][N], h[N], ts[N], te[N], t[N], ct, tp[N];
void dfs(int x) {
  ts[x] = t[x] = ++ct;
  tp[t[x]] = x;
  pts.push_back(x);
  pin[h[x]].push_back(t[x]);
  for (int to : ed[x]) {
    h[to] = h[x] + 1;
    dfs(to);
  }
  te[x] = ct;
}
void process() {
  for (int b = 1; b < B; b++)
    for (int x : pts)
      par[b][x] = (par[b - 1][x] == -1) ? -1 : par[b - 1][par[b - 1][x]];
}
int solve(int x, int p) {
  if (h[x] < p) return 0;
  int oh = h[x];
  for (int b = B - 1; b >= 0; b--) {
    if (p >= (1 << b)) {
      x = par[b][x];
      p -= (1 << b);
    }
  }
  int st = lower_bound(pin[oh].begin(), pin[oh].end(), ts[x]) - pin[oh].begin();
  int et = upper_bound(pin[oh].begin(), pin[oh].end(), te[x]) - pin[oh].begin();
  return et - st - 1;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", par[0] + i);
    if (par[0][i])
      ed[par[0][i]].push_back(i);
    else
      par[0][i] = -1;
  }
  for (int i = 1; i <= n; i++) {
    if (par[0][i] == -1) {
      dfs(i);
      process();
      pts.clear();
    }
  }
  scanf("%d", &m);
  for (int i = 0; i < m; i++) {
    int x, p;
    scanf("%d%d", &x, &p);
    printf("%d ", solve(x, p));
  }
  puts("");
}
