#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 20, B = 20;
int n, a[N], q, v, p, str[N], fin[N], t, h[N], par[N][B], tmp1, tmp2;
vector<int> adj[N], dis[N];
void dfs(int u, int p) {
  str[u] = t;
  t++;
  for (int i = 1; i < B; i++) {
    if (par[u][i - 1] == -1) {
      break;
    }
    par[u][i] = par[par[u][i - 1]][i - 1];
  }
  for (auto x : adj[u]) {
    if (x != p) {
      h[x] = h[u] + 1;
      par[x][0] = u;
      dfs(x, u);
      dis[h[x]].push_back(str[x]);
    }
  }
  fin[u] = t;
}
inline int e_dis(int v, int d) {
  for (int i = 0; i < B; i++) {
    if (d & (1 << i)) {
      v = par[v][i];
    }
  }
  return v;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    adj[a[i]].push_back(i);
    adj[i].push_back(a[i]);
  }
  for (int i = 1; i <= n; i++) {
    if (a[i] == 0) {
      h[i] = 0;
      dis[h[i]].push_back(i);
      dfs(i, 0);
    }
  }
  cin >> q;
  while (q--) {
    cin >> v >> p;
    p = e_dis(v, p);
    if (p == 0) {
      cout << 0 << endl;
      continue;
    }
    tmp1 = lower_bound(dis[h[v]].begin(), dis[h[v]].end(), str[p]) -
           dis[h[v]].begin();
    tmp2 = lower_bound(dis[h[v]].begin(), dis[h[v]].end(), fin[p]) -
           dis[h[v]].begin();
    cout << (tmp2 - 1) - tmp1 + 1 - 1 << endl;
  }
  return 0;
}
