#include <bits/stdc++.h>
using namespace std;
void fast() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
const long long N = 1e6;
const long long BLK = 666;
long long dr[4] = {1, 0, 0, -1};
long long dc[4] = {0, -1, 1, 0};
long long ddr[8] = {0, 0, 1, -1, 1, -1, 1, -1};
long long ddc[8] = {1, -1, 0, 0, 1, -1, -1, 1};
long long ddr1[8] = {1, 1, -1, -1, 2, 2, -2, -2};
long long ddc1[8] = {2, -2, 2, -2, 1, -1, 1, -1};
vector<long long> inn[N], outt[N];
map<long long, long long> in, out;
long long timer, vis[N], level[N];
vector<long long> v[N];
void dfs(long long node, long long lvl) {
  level[node] = lvl;
  in[node] = timer++;
  inn[level[node]].emplace_back(in[node]);
  vis[node] = 1;
  for (auto i : v[node]) {
    if (vis[i] == 0) {
      dfs(i, lvl + 1);
    }
  }
  out[node] = timer++;
  outt[level[node]].emplace_back(out[node]);
}
int32_t main() {
  fast();
  long long n;
  cin >> n;
  for (long long i = 1; i < n + 1; i++) {
    long long x;
    cin >> x;
    if (x > 0) {
      v[i].emplace_back(x);
      v[x].emplace_back(i);
    }
  }
  timer = 1;
  for (long long i = 1; i <= n; i++) {
    if (vis[i] == 0) {
      dfs(i, 1);
    }
  }
  long long q, nod, p, cl, rl, ci, co, po, pii;
  cin >> q;
  while (q--) {
    cin >> nod >> p;
    cl = level[nod];
    rl = cl - p;
    if (rl < 0 || inn[rl].size() == 0) {
      cout << "0 ";
      continue;
    }
    ci = in[nod];
    co = out[nod];
    long long p1 =
        upper_bound(inn[rl].begin(), inn[rl].end(), ci) - inn[rl].begin();
    p1--;
    long long p2 =
        upper_bound(outt[rl].begin(), outt[rl].end(), co) - outt[rl].begin();
    if (p1 != p2) {
      cout << "0 ";
      continue;
    }
    pii = inn[rl][p1];
    po = outt[rl][p2];
    long long ans = 0;
    p1 = lower_bound(inn[cl].begin(), inn[cl].end(), pii) - inn[cl].begin();
    p2 = upper_bound(outt[cl].begin(), outt[cl].end(), po) - outt[cl].begin();
    ans += p2 - p1;
    ans--;
    cout << ans << " ";
  }
}
