#include <bits/stdc++.h>
using namespace std;
int fa[18][100005], dep[100005], n, q, t, ia[100005], ib[100005];
vector<int> ve[100005], vec[100005], aq;
void update() {
  for (int i = 0; i <= 17; i++) {
    for (int j = 1; j <= n; j++) {
      if (fa[i][j] != -1) fa[i + 1][j] = fa[i][fa[i][j]];
    }
  }
}
void dfs(int pt, int f) {
  if (f == -1)
    dep[pt] = 0;
  else
    dep[pt] = dep[f] + 1;
  ia[pt] = t++;
  vec[dep[pt]].push_back(ia[pt]);
  for (int i = 0; i < ve[pt].size(); i++) dfs(ve[pt][i], pt);
  ib[pt] = t;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n;
  memset(fa, -1, sizeof(fa));
  for (int i = 1; i <= n; i++) {
    cin >> fa[0][i];
    if (fa[0][i] == 0) {
      fa[0][i] = -1;
      continue;
    } else
      ve[fa[0][i]].push_back(i);
  }
  for (int i = 1; i <= n; i++) {
    if (fa[0][i] == -1) {
      dfs(i, -1);
    }
  }
  update();
  cin >> q;
  bool sp = false;
  while (q--) {
    int v, p;
    cin >> v >> p;
    if (dep[v] < p) {
      aq.push_back(0);
      continue;
    }
    int va = v, de = dep[v];
    for (int i = 17; i >= 0; i--)
      if (p & (1 << i)) va = fa[i][va];
    int ans = int(lower_bound(vec[de].begin(), vec[de].end(), ib[va]) -
                  vec[de].begin()) -
              int(lower_bound(vec[de].begin(), vec[de].end(), ia[va]) -
                  vec[de].begin()) -
              1;
    aq.push_back(ans);
  }
  for (int i = 0; i < aq.size(); i++) {
    if (i > 0) cout << " ";
    cout << aq[i];
  }
  cout << endl;
  return 0;
}
