#include <bits/stdc++.h>
using namespace std;
int anc[19][100005], bt[100005], dt[100005], ht[100005], t;
int n, q, res[100005];
vector<int> v[100005], bh[100005];
struct qq {
  int node, lev, id;
};
vector<qq> query;
void dfs(int id, int pv) {
  if (pv != -1) {
    ht[id] = ht[pv] + 1;
    bt[id] = ++t;
    bh[ht[id]].push_back(bt[id]);
  }
  for (int i = (0); i <= ((int)v[id].size() - 1); i++) {
    int to = v[id][i];
    dfs(to, id);
  }
  if (pv != -1) dt[id] = ++t;
  return;
}
int search(int x, int dep) {
  int l = -1, r = bh[dep].size();
  while (r - l > 1) {
    int m = (l + r) >> 1;
    if (bh[dep][m] < x)
      l = m;
    else
      r = m;
  }
  return l + 1;
}
int main() {
  scanf("%d", &n);
  for (int i = (1); i <= (n); i++) {
    scanf("%d", &anc[0][i]);
    v[anc[0][i]].push_back(i);
  }
  dfs(0, -1);
  for (int i = (1); i <= (17); i++)
    for (int j = (0); j <= (n); j++) anc[i][j] = anc[i - 1][anc[i - 1][j]];
  scanf("%d", &q);
  for (int i = (1); i <= (q); i++) {
    int a, b;
    scanf("%d %d", &a, &b);
    if (ht[a] <= b)
      res[i] = 0;
    else {
      int ono = a;
      for (int j = (17); j >= (0); j--)
        if (b >= (1 << j)) {
          b -= 1 << j;
          ono = anc[j][ono];
        }
      res[i] = search(dt[ono], ht[a]) - search(bt[ono], ht[a]) - 1;
    }
    printf("%d%c", res[i], i == q ? '\n' : ' ');
  }
  return 0;
}
