#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 3;
const int maxm = 1e7 + 3;
const int mod = 1e9 + 7;
const int oo = 1e9 + 5;
const long double pi = 3.141592653589793238462643383279502884;
void input() {
  if (fopen("abc"
            ".inp",
            "r")) {
    freopen(
        "abc"
        ".inp",
        "r", stdin);
    freopen(
        "abc"
        ".out",
        "w", stdout);
  }
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
int n, m, _time = 0;
vector<int> g[maxn], val[maxn];
int in[maxn], out[maxn], anc[maxn][20], h[maxn];
void dfs(int u) {
  in[u] = ++_time;
  val[h[u]].push_back(in[u]);
  for (int v : g[u]) {
    h[v] = h[u] + 1;
    dfs(v);
  }
  out[u] = _time;
}
int jump(int u, int d) {
  for (int i = 18; i >= 0; --i)
    if ((d >> i) & 1) u = anc[u][i];
  return u;
}
int main() {
  input();
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> anc[i][0];
    g[anc[i][0]].push_back(i);
  }
  for (int j = 1; j < 19; ++j)
    for (int i = 1; i <= n; ++i) anc[i][j] = anc[anc[i][j - 1]][j - 1];
  dfs(0);
  cin >> m;
  int v, p;
  while (m--) {
    cin >> v >> p;
    int u = jump(v, p);
    if (!u)
      cout << "0\n";
    else {
      auto l = lower_bound(val[h[v]].begin(), val[h[v]].end(), in[u]) -
               val[h[v]].begin();
      auto r = upper_bound(val[h[v]].begin(), val[h[v]].end(), out[u]) -
               val[h[v]].begin() - 1;
      cout << r - l << "\n";
    }
  }
  return 0;
}
