#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const long long mod = 1e9 + 7;
const long long maxn = 1e5 + 10;
const long long K = 755;
long long n;
long long p[maxn], h[maxn], par[maxn][22], st[maxn];
vector<long long> g[maxn], ve;
void dfs(long long u) {
  par[u][0] = p[u];
  for (long long i = 1; (1 << i) <= h[u]; i++)
    par[u][i] = par[par[u][i - 1]][i - 1];
  st[u] = 1;
  for (long long i = 0; i < g[u].size(); i++)
    if (g[u][i] != p[u]) {
      h[g[u][i]] = h[u] + 1;
      p[g[u][i]] = u;
      dfs(g[u][i]);
      st[u] += st[g[u][i]];
    }
  ve.push_back(u);
}
long long get_par(long long u, long long he) {
  if (he == 0) return u;
  if (he == 1) return par[u][0];
  long long x = log2(he);
  return get_par(par[u][x], he - (1 << x));
}
vector<long long> bin[maxn];
long long idx[maxn];
int main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> p[i];
    if (p[i]) {
      g[p[i]].push_back(i);
      g[i].push_back(p[i]);
    }
  }
  for (long long i = 1; i <= n; i++)
    if (p[i] == 0) dfs(i);
  for (long long i = 0; i < n; i++) {
    idx[ve[i]] = i;
    bin[h[ve[i]]].push_back(i);
  }
  long long q;
  cin >> q;
  while (q--) {
    long long v, k;
    cin >> v >> k;
    if (h[v] < k) {
      cout << 0 << "\n";
      continue;
    }
    long long x = get_par(v, k);
    long long l = idx[x] - st[x] + 1, r = idx[x];
    long long xx =
        lower_bound(bin[h[v]].begin(), bin[h[v]].end(), l) - bin[h[v]].begin();
    long long yy = upper_bound(bin[h[v]].begin(), bin[h[v]].end(), r) -
                   bin[h[v]].begin() - 1;
    cout << yy - xx << "\n";
  }
}
