#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000033, LN = 20;
int pa[LN][MAXN], st[MAXN], en[MAXN], dep[MAXN], pool;
vector<int> g[MAXN], at[MAXN];
void dfs(int u, int d) {
  dep[u] = d;
  st[u] = ++pool;
  at[d].push_back(pool);
  for (auto v : g[u]) dfs(v, d + 1);
  en[u] = pool;
}
int kthAncestor(int u, int k) {
  for (int i = LN - 1; i >= 0; --i)
    if (k & (1 << i)) u = pa[i][u];
  return u;
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &pa[0][i]), g[pa[0][i]].push_back(i);
  for (int i = 1; i <= n; ++i)
    if (!st[i]) dfs(i, 1);
  for (int j = 1; j < LN; ++j)
    for (int i = 1; i <= n; ++i) pa[j][i] = pa[j - 1][pa[j - 1][i]];
  int q;
  scanf("%d", &q);
  while (q--) {
    int v, k;
    scanf("%d %d", &v, &k);
    int p = kthAncestor(v, k);
    int l = st[p], r = en[p], d = dep[v];
    if (p == 0)
      printf("0 ");
    else
      printf("%lu ", upper_bound(at[d].begin(), at[d].end(), r) -
                         lower_bound(at[d].begin(), at[d].end(), l) - 1);
  }
}
