#include <bits/stdc++.h>
using namespace std;
vector<int> v[100005];
int n;
int parent[100005];
int in[100005];
int depth[100005];
int cnt[100005];
int mark;
vector<int> h[100005];
vector<int> id[100005];
void dfs(int x, int hg, int par) {
  int sz = v[x].size();
  int i, j;
  h[hg].push_back(mark);
  id[hg].push_back(x);
  in[x] = mark;
  depth[x] = hg;
  cnt[x] = 1;
  mark++;
  for (i = 0; i < sz; i++) {
    int y = v[x][i];
    if (y == par) continue;
    dfs(y, hg + 1, x);
    cnt[x] += cnt[y];
  }
}
int bs1(int indx, int val) {
  int ret = -1, l = 0, r = h[indx].size() - 1;
  while (l <= r) {
    int mid = (l + r) / 2;
    if (h[indx][mid] <= val) {
      ret = mid;
      l = mid + 1;
    } else {
      r = mid - 1;
    }
  }
  return ret + 1;
}
int main() {
  scanf("%d", &n);
  int i, j;
  int x;
  for (i = 1; i <= n; i++) {
    scanf("%d", &parent[i]);
    if (parent[i] == 0) continue;
    x = parent[i];
    v[i].push_back(x);
    v[x].push_back(i);
  }
  mark = 0;
  for (i = 1; i <= n; i++) {
    if (parent[i] == 0) {
      dfs(i, 0, -1);
    }
  }
  int m;
  scanf("%d", &m);
  int y;
  for (i = 0; i < m; i++) {
    scanf("%d %d", &x, &y);
    if (depth[x] < y) {
      printf("0 ");
    } else {
      int inh = depth[x] - y;
      int par = bs1(inh, in[x]);
      par = id[inh][par - 1];
      int cnt1 = bs1(depth[x], in[par] + cnt[par] - 1);
      int cnt2 = bs1(depth[x], in[par] - 1);
      int ans = cnt1 - cnt2 - 1;
      printf("%d ", ans);
    }
  }
  printf("\n");
  return 0;
}
