#include <bits/stdc++.h>
using namespace std;
const int mxN = 1e5;
const int lvl = 17;
vector<int> cnt[mxN];
vector<int> adj[mxN];
int dpt[mxN];
int id[mxN];
int idx = 1;
int sub[mxN];
int n;
int prnt[mxN][lvl + 1];
int dfs(int u, int e, int d) {
  dpt[u] = d;
  sub[u] = 1;
  id[u] = idx++;
  cnt[dpt[u]].push_back(id[u]);
  prnt[u][0] = e;
  for (int i = 1; i <= lvl; i++) {
    if (prnt[u][i - 1] != -1) {
      prnt[u][i] = prnt[prnt[u][i - 1]][i - 1];
    }
  }
  for (auto ad = adj[u].begin(); ad != adj[u].end(); ad++) {
    sub[u] += dfs(*ad, u, d + 1);
  }
  return sub[u];
}
int calc(int u, int p) {
  int v = u;
  for (int i = lvl; i >= 0; i--) {
    if (p >= (1 << i)) {
      if (prnt[v][i] == -1) return 0;
      v = prnt[v][i];
      p -= 1 << i;
    }
  }
  auto mi = lower_bound(cnt[dpt[u]].begin(), cnt[dpt[u]].end(), id[v]);
  auto ma = lower_bound(cnt[dpt[u]].begin(), cnt[dpt[u]].end(), id[v] + sub[v]);
  ma--;
  return distance(mi, ma);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n;
  vector<int> st;
  memset(prnt, -1, mxN * (lvl + 1) * 4);
  for (int i = 0; i < n; i++) {
    int x;
    cin >> x;
    x--;
    if (x == -1)
      st.push_back(i);
    else
      adj[x].push_back(i);
  }
  for (int i = 0; i < st.size(); i++) {
    dfs(st[i], -1, 0);
  }
  int m;
  cin >> m;
  while (m--) {
    int v, p;
    cin >> v >> p;
    v--;
    cout << calc(v, p) << " ";
  }
  return 0;
}
