#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int fa[N][20], dep[N], num[N], en[N], cnt;
vector<int> a[N], e[N];
void dfs(int u) {
  for (int i = 1; (1 << i) < dep[u]; i++) fa[u][i] = fa[fa[u][i - 1]][i - 1];
  num[u] = ++cnt;
  a[dep[u]].push_back(num[u]);
  for (int i = 0; i < e[u].size(); i++) {
    int v = e[u][i];
    dep[v] = dep[u] + 1;
    dfs(v);
  }
  en[u] = cnt;
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &fa[i][0]);
    e[fa[i][0]].push_back(i);
  }
  for (int i = 1; i <= n; i++) {
    if (!fa[i][0]) {
      dep[i] = 1;
      dfs(i);
    }
  }
  int m;
  scanf("%d", &m);
  for (int i = 1; i <= m; i++) {
    int v, p;
    scanf("%d%d", &v, &p);
    int x = v;
    for (int j = 17; j >= 0; j--)
      if (dep[fa[x][j]] >= dep[v] - p) x = fa[x][j];
    int ans = upper_bound(a[dep[v]].begin(), a[dep[v]].end(), en[x]) -
              lower_bound(a[dep[v]].begin(), a[dep[v]].end(), num[x]) - 1;
    printf("%d ", max(ans, 0));
  }
  return 0;
}
