#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000 * 100 + 100;
vector<int> adj[MAXN], d[MAXN], path;
int start[MAXN], fin[MAXN], deep[MAXN], cnt = 1, par[MAXN][21];
void dfs(int dd, int u) {
  for (int i = 0; i < 21; i++) {
    int x = (1 << i);
    if (x <= path.size()) par[u][i] = path[path.size() - x];
  }
  path.push_back(u);
  deep[u] = dd;
  start[u] = cnt++;
  d[dd].push_back(start[u]);
  for (int i = 0; i < adj[u].size(); i++) dfs(dd + 1, adj[u][i]);
  path.pop_back();
  fin[u] = cnt++;
}
int find_par(int a, int b) {
  if (b == 0) return a;
  int x = 0;
  for (int i = 0; i < 20; i++)
    if ((1 << i) <= b and (1 << (i + 1)) > b)
      return find_par(par[a][i], b - (1 << i));
}
int find(int r, int dd) {
  if (r == 0) return 1;
  int up = upper_bound(d[dd].begin(), d[dd].end(), fin[r]) - d[dd].begin();
  int down = lower_bound(d[dd].begin(), d[dd].end(), start[r]) - d[dd].begin();
  return up - down;
}
int main() {
  int n, m;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int r;
    scanf("%d", &r);
    adj[r].push_back(i);
  }
  dfs(0, 0);
  for (int i = 0; i <= n; i++) sort(d[i].begin(), d[i].end());
  scanf("%d", &m);
  for (int i = 0; i < m; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    int p = find_par(a, b);
    int x = find(p, deep[a]) - 1;
    printf("%d ", x);
  }
  printf("\n");
  return 0;
}
