#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:50000000")
using namespace std;
const int N = 100010;
int n, i, m, tim, r[N], v[N], p[N], d[N], tin[N], tout[N], a[N];
vector<int> g[N], h[N], sp[N];
map<pair<int, int>, int> f;
void dfs(int v, int dist) {
  int i;
  tin[v] = tim++;
  d[v] = dist;
  a[dist] = v;
  sp[dist].push_back(tin[v]);
  for (i = 0; i < (int)g[v].size(); i++) dfs(g[v][i], dist + 1);
  for (i = 0; i < (int)h[v].size(); i++)
    if (h[v][i] <= dist) f[make_pair(v, h[v][i])] = a[dist - h[v][i]];
  tout[v] = tim - 1;
}
int main() {
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> r[i];
    if (r[i]) g[r[i] - 1].push_back(i);
  }
  cin >> m;
  for (i = 0; i < m; i++) {
    cin >> v[i] >> p[i];
    v[i]--;
    h[v[i]].push_back(p[i]);
  }
  tim = 0;
  for (i = 0; i < n; i++)
    if (!r[i]) dfs(i, 0);
  for (i = 0; i < m; i++) {
    if (p[i] > d[v[i]]) {
      cout << "0 ";
      continue;
    }
    int x = f[make_pair(v[i], p[i])], dist = d[v[i]], l = -1,
        r = (int)sp[dist].size(), mid;
    while (r - l > 1) {
      mid = (r + l) / 2;
      if (sp[dist][mid] < tin[x])
        l = mid;
      else
        r = mid;
    }
    int y = r;
    l = -1;
    r = (int)sp[dist].size();
    while (r - l > 1) {
      mid = (r + l) / 2;
      if (sp[dist][mid] > tout[x])
        r = mid;
      else
        l = mid;
    }
    cout << l - y << " ";
  }
  return 0;
}
