#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
int node[(ll)(1e5 + 7)], in[(ll)(1e5 + 7)], out[(ll)(1e5 + 7)],
    ti = 1, hie[(ll)(1e5 + 7)];
int dp[(ll)(1e5 + 7)][17];
vector<int> gr[(ll)(1e5 + 7)], hi[(ll)(1e5 + 7)];
void dfs(int node, int h) {
  hi[h].push_back(ti);
  hie[node] = h;
  in[node] = ti++;
  for (int x : gr[node]) {
    dfs(x, h + 1);
  }
  out[node] = ti++;
}
int main() {
  ios_base ::sync_with_stdio(false);
  cin.tie(nullptr);
  int n;
  cin >> n;
  vector<int> ve;
  for (int i = 1; i <= n; i++) {
    for (int j = 0; j < 17; j++) {
      dp[i][j] = -1;
    }
  }
  for (int i = 1; i <= n; i++) {
    int val;
    cin >> val;
    if (val) {
      dp[i][0] = val;
      gr[val].push_back(i);
    } else {
      ve.push_back(i);
    }
  }
  for (int x : ve) {
    dfs(x, 1);
  }
  for (int j = 1; j < 17; j++) {
    for (int i = 1; i <= n; i++) {
      if (dp[i][j - 1] != -1) {
        dp[i][j] = dp[dp[i][j - 1]][j - 1];
      }
    }
  }
  int q;
  cin >> q;
  for (int i = 0; i < q; i++) {
    int x, p;
    cin >> x >> p;
    for (int j = 0; (1 << j) <= p; j++) {
      if ((1 << j) & p) {
        x = dp[x][j];
      }
    }
    if (x == -1) {
      cout << "0 ";
      continue;
    }
    int hh = hie[x] + p;
    int xx = (upper_bound(hi[hh].begin(), hi[hh].end(), out[x]) -
              lower_bound(hi[hh].begin(), hi[hh].end(), in[x]));
    cout << max(0, xx - 1) << " ";
  }
  cout << "\n";
}
