#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int n, m, root;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) (ch == '-') && (f = -f), ch = getchar();
  while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
  return x * f;
}
int head[MAXN], trump;
struct Edge {
  int to, next;
  Edge(int u = 0, int v = 0) : to(v), next(head[u]){};
} e[MAXN];
inline void addedge(int u, int v) {
  u = u ? u : root;
  e[++trump] = Edge(u, v);
  head[u] = trump;
}
int prt[MAXN];
struct Query {
  int k, ord;
  Query(int k = 0, int ord = 0) : k(k), ord(ord){};
};
vector<Query> S[MAXN];
vector<Query> Q[MAXN];
int dep[MAXN], size[MAXN], son[MAXN];
int s[MAXN], top;
void tarjan(int u) {
  s[++top] = u;
  size[u] = 1;
  for (vector<Query>::iterator it = S[u].begin(); it != S[u].end(); ++it) {
    int k = (*it).k, ord = (*it).ord;
    if (top - k > 1) Q[s[top - k]].push_back(Query(k, ord));
  }
  for (register int i = head[u]; i; i = e[i].next) {
    dep[e[i].to] = dep[u] + 1;
    tarjan(e[i].to);
    size[u] += size[e[i].to];
    (size[son[u]] < size[e[i].to]) && (son[u] = e[i].to);
  }
  s[top--] = 0;
}
int cnt[MAXN];
void work(int u, int w) {
  ++cnt[dep[u]];
  for (register int i = head[u]; i; i = e[i].next)
    (e[i].to != w) && (work(e[i].to, w), 1);
}
void clear(int u) {
  --cnt[dep[u]];
  for (register int i = head[u]; i; i = e[i].next) clear(e[i].to);
}
void dsu(int u) {
  for (register int i = head[u]; i; i = e[i].next)
    (e[i].to != son[u]) && (dsu(e[i].to), clear(e[i].to), 1);
  son[u] && (dsu(son[u]), 1);
  work(u, son[u]);
  for (vector<Query>::iterator it = Q[u].begin(); it != Q[u].end(); ++it)
    prt[(*it).ord] = cnt[dep[u] + (*it).k] - 1;
}
int main() {
  register int i;
  n = read();
  root = n + 1;
  for (i = 1; i <= n; ++i) addedge(read(), i);
  m = read();
  for (i = 1; i <= m; ++i) {
    int u = read(), k = read();
    S[u].push_back(Query(k, i));
  }
  tarjan(root);
  dsu(root);
  for (i = 1; i <= m; ++i) printf("%d ", prt[i]);
  return 0;
}
