#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const int LogN = 17 + 1;
vector<int> g[N];
int pr[LogN][N];
int tin[N];
int tout[N];
int dist[N];
int n, q;
void dfs(int u) {
  static int timer = 0;
  tin[u] = ++timer;
  for (int v : g[u]) {
    if (!tin[v]) {
      dist[v] = dist[u] + 1;
      dfs(v);
    }
  }
  tout[u] = timer;
}
struct segment_tree {
  struct node {
    map<int, int> cnt;
    node() {}
  };
  node st[N << 2];
  void update(int x, int l, int r, int k, int v) {
    st[x].cnt[v]++;
    if (l == r) {
      return;
    }
    int mid = (l + r) / 2;
    if (k <= mid) {
      update(x << 1, l, mid, k, v);
    } else {
      update(x << 1 | 1, mid + 1, r, k, v);
    }
  }
  void update(int u) { update(1, tin[0], tout[0], tin[u], dist[u]); }
  int query(int x, int l, int r, int ll, int rr, int v) {
    if (r < ll || rr < l || r < l) {
      return 0;
    }
    if (ll <= l && r <= rr) {
      return st[x].cnt.count(v) ? st[x].cnt[v] : 0;
    }
    int mid = (l + r) / 2;
    return query(x << 1, l, mid, ll, rr, v) +
           query(x << 1 | 1, mid + 1, r, ll, rr, v);
  }
  int query(int z, int u) {
    return query(1, tin[0], tout[0], tin[z], tout[z], dist[u]);
  }
};
segment_tree st;
void build_lca() {
  for (int k = (1); k <= ((LogN - 1)); k += (+1)) {
    for (int u = (1); u <= ((n)); u += (+1)) {
      if (pr[k - 1][u] != 0) {
        pr[k][u] = pr[k - 1][pr[k - 1][u]];
      }
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0), cout.precision(15);
  cin >> n;
  for (int u = (1); u <= ((n)); u += (+1)) {
    cin >> pr[0][u];
    g[pr[0][u]].push_back(u);
  }
  dfs(0);
  build_lca();
  for (int u = (1); u <= ((n)); u += (+1)) {
    st.update(u);
  }
  cin >> q;
  while (q--) {
    int u, p_anc;
    cin >> u >> p_anc;
    int cousins = 0;
    if (dist[u] > p_anc) {
      int z = u;
      for (int k = (LogN - 1); k >= (0); k += (-1)) {
        if ((1 << k) <= p_anc) {
          p_anc -= (1 << k);
          z = pr[k][z];
        }
      }
      cousins = st.query(z, u) - 1;
    }
    cout << cousins << " \n"[q == 0];
  }
  return 0;
}
