#include <bits/stdc++.h>
using namespace std;
int n, m, h[100015], p[20][100015], dfsCnt, num[100015], cnt[100015];
vector<int> a[100015], s[100015];
void dfsLCA(int u) {
  num[u] = ++dfsCnt;
  cnt[u] = 1;
  s[h[u]].push_back(num[u]);
  for (int v : a[u]) h[v] = h[u] + 1, dfsLCA(v), cnt[u] += cnt[v];
}
void initLCA() {
  for (int u = 1; u <= n; ++u)
    if (!p[0][u]) h[u] = 1, dfsLCA(u);
  for (int k = 1, p2k = 2; p2k <= n; ++k, p2k <<= 1)
    for (int u = 1; u <= n; ++u) p[k][u] = p[k - 1][p[k - 1][u]];
}
int ancestor(int u, int x) {
  for (int k; x; x ^= 1 << k) k = log2(x), u = p[k][u];
  return u;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> p[0][i], a[p[0][i]].push_back(i);
  initLCA();
  for (int i = 1; i <= n; ++i) sort(s[i].begin(), s[i].end());
  cin >> m;
  for (int v, k, x; m--;) {
    cin >> v >> k;
    x = ancestor(v, k);
    if (!x)
      cout << "0 ";
    else
      cout << lower_bound(s[h[v]].begin(), s[h[v]].end(), num[x] + cnt[x]) -
                  lower_bound(s[h[v]].begin(), s[h[v]].end(), num[x]) - 1
           << ' ';
  }
}
