#include <bits/stdc++.h>
using namespace std;
const int M = 100005;
int read() {
  int num = 0, flag = 1;
  char c;
  while ((c = getchar()) < '0' || c > '9')
    if (c == '-') flag = -1;
  while (c >= '0' && c <= '9')
    num = (num << 3) + (num << 1) + (c ^ 48), c = getchar();
  return num * flag;
}
int n, m, tot, f[M], ans[M], dep[M], fa[M][20], siz[M], son[M], cnt[M];
struct node {
  int d, id;
};
vector<node> q[M];
struct edge {
  int v, next;
} e[2 * M];
void dfs1(int u, int p) {
  siz[u] = 1;
  fa[u][0] = p;
  dep[u] = dep[p] + 1;
  for (int i = 1; i <= 19; i++) fa[u][i] = fa[fa[u][i - 1]][i - 1];
  for (int i = f[u]; i; i = e[i].next) {
    int v = e[i].v;
    if (v == p) continue;
    dfs1(v, u);
    siz[u] += siz[v];
    if (siz[v] > siz[son[u]]) son[u] = v;
  }
}
int up(int u, int p) {
  for (int i = 19; i >= 0; i--)
    if (p & (1 << i)) u = fa[u][i];
  return u;
}
void fuck(int u, int fl) {
  cnt[dep[u]] += fl;
  for (int i = f[u]; i; i = e[i].next) {
    int v = e[i].v;
    if (v == fa[u][0]) continue;
    fuck(v, fl);
  }
}
void dfs2(int u) {
  for (int i = f[u]; i; i = e[i].next) {
    int v = e[i].v;
    if (v == fa[u][0] || v == son[u]) continue;
    dfs2(v);
    fuck(v, -1);
  }
  if (son[u]) dfs2(son[u]);
  cnt[dep[u]]++;
  for (int i = f[u]; i; i = e[i].next) {
    int v = e[i].v;
    if (v == fa[u][0] || v == son[u]) continue;
    fuck(v, 1);
  }
  for (int i = 0; i < q[u].size(); i++) {
    int d = q[u][i].d, id = q[u][i].id;
    ans[id] = cnt[d] - 1;
  }
}
signed main() {
  n = read();
  for (int i = 1; i <= n; i++) {
    int j = read();
    if (!j) continue;
    e[++tot] = edge{i, f[j]}, f[j] = tot;
    e[++tot] = edge{j, f[i]}, f[i] = tot;
  }
  for (int i = 1; i <= n; i++)
    if (!dep[i]) dfs1(i, 0);
  m = read();
  for (int i = 1; i <= m; i++) {
    int u = read(), p = up(u, read());
    if (p) q[p].push_back(node{dep[u], i});
  }
  for (int i = 1; i <= n; i++)
    if (dep[i] == 1) {
      dfs2(i);
      fuck(i, -1);
    }
  for (int i = 1; i <= m; i++) printf("%d ", ans[i]);
}
