#include <bits/stdc++.h>
using namespace std;
vector<int> a[100001], c[100001];
int n, i, u, v, h[100001], l[100001], r[100001], cnt, p[100001][21], rt, q, x;
void DFS(int u) {
  h[u] = h[p[u][0]] + 1;
  for (int i = 1; (1 << i) <= n; i++) p[u][i] = p[p[u][i - 1]][i - 1];
  l[u] = r[u] = ++cnt;
  c[h[u]].push_back(cnt);
  for (int i = 0; i < a[u].size(); i++) {
    int v = a[u][i];
    if (v != p[u][0]) {
      p[v][0] = u;
      DFS(v);
      r[u] = max(r[u], r[v]);
    }
  }
}
int bsl(int k, int h) {
  int l = 0, r = c[h].size() - 1;
  while (l < r) {
    int mid = (l + r) >> 1;
    if (c[h][mid] >= k)
      r = mid;
    else
      l = mid + 1;
  }
  return l;
}
int bsr(int k, int h) {
  int l = 0, r = c[h].size() - 1;
  while (l < r) {
    int mid = (l + r + 1) >> 1;
    if (c[h][mid] <= k)
      l = mid;
    else
      r = mid - 1;
  }
  return l;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> u;
    p[i][0] = u;
    a[u].push_back(i);
  }
  for (i = 1; i <= n; i++)
    if (p[i][0] == 0) DFS(i);
  for (i = 1; i <= n; i++) sort(c[i].begin(), c[i].end());
  cin >> q;
  while (q--) {
    cin >> u >> x;
    if (h[u] < x + 1) {
      cout << 0 << ' ';
      continue;
    }
    v = u;
    for (i = trunc(log2(h[u])) + 1; i >= 0; i--)
      if (h[v] - (1 << i) >= h[u] - x) v = p[v][i];
    cout << bsr(r[v], h[u]) - bsl(l[v], h[u]) << ' ';
  }
}
