#include <bits/stdc++.h>
const int mod = 988244353;
using namespace std;
inline int read() {
  int f = 1, x = 0;
  char s = getchar();
  while (!isdigit(s)) {
    if (s == '-') f = -1;
    s = getchar();
  }
  while (isdigit(s)) {
    x = (x << 1) + (x << 3) + (s ^ 48), s = getchar();
  }
  return x * f;
}
int n, m, head[200020], cnt;
struct edge {
  int to, nxt;
} e[200020 << 1];
inline void add_edge(int u, int v) {
  e[++cnt].nxt = head[u], head[u] = cnt, e[cnt].to = v;
}
int dep[200020], f[200020][31], ans[200020], k[200020];
vector<int> st[200020];
int root[200020], sum[200020 << 5], lc[200020 << 5], rc[200020 << 5], tot;
inline void modify(int &rt, int l, int r, int x) {
  if (!rt) rt = ++tot;
  if (l == r) return void(sum[rt]++);
  int mid = (l + r) >> 1;
  if (x <= mid)
    modify(lc[rt], l, mid, x);
  else
    modify(rc[rt], mid + 1, r, x);
  sum[rt] = sum[lc[rt]] + sum[rc[rt]];
}
inline int merge(int rt, int pre) {
  if (!rt || !pre) return rt + pre;
  sum[rt] = sum[rt] + sum[pre];
  lc[rt] = merge(lc[rt], lc[pre]);
  rc[rt] = merge(rc[rt], rc[pre]);
  return rt;
}
inline int query(int rt, int l, int r, int x) {
  if (l == r) return sum[rt];
  int mid = (l + r) >> 1, ans = 0;
  if (x <= mid)
    ans += query(lc[rt], l, mid, x);
  else
    ans += query(rc[rt], mid + 1, r, x);
  return ans;
}
inline void dfs(int rt, int fa) {
  dep[rt] = dep[fa] + 1, f[rt][0] = fa;
  for (int i = 1; i <= 30; i++) f[rt][i] = f[f[rt][i - 1]][i - 1];
  for (int i = head[rt]; i; i = e[i].nxt) {
    if (e[i].to == fa) continue;
    dfs(e[i].to, rt);
  }
}
inline int get_anc(int x, int k) {
  int to = dep[x] - k;
  for (int i = 30; i >= 0; i--)
    if (dep[f[x][i]] >= to) x = f[x][i];
  return x;
}
inline void redfs(int rt, int fa) {
  for (int i = head[rt]; i; i = e[i].nxt) {
    if (e[i].to == fa) continue;
    redfs(e[i].to, rt), root[rt] = merge(root[rt], root[e[i].to]);
  }
  modify(root[rt], 1, n + 1, dep[rt]);
  if (rt != 0)
    for (int i = 0; i < st[rt].size(); i++)
      ans[st[rt][i]] = query(root[rt], 1, n + 1, dep[rt] + k[st[rt][i]]) - 1;
}
signed main(void) {
  n = read();
  for (int i = 1; i <= n; i++) {
    int f = read();
    add_edge(f, i), add_edge(i, f);
  }
  dfs(0, 0), m = read();
  for (int i = 1; i <= m; i++) {
    int x = read();
    k[i] = read();
    if (dep[x] > k[i]) st[get_anc(x, k[i])].push_back(i);
  }
  redfs(0, 0);
  for (int i = 1; i <= m; i++) printf("%d ", ans[i]);
  return 0;
}
