#include <bits/stdc++.h>
using namespace std;
template <typename T, typename L>
bool smax(T &x, L y) {
  return x < y ? (x = y, true) : false;
}
struct Q {
  int p, id;
};
int get(int, int);
void dfs(int);
void sack(int, bool);
const int MAXN = 1e5 + 15, LG = 20;
int h[MAXN], cnt[MAXN];
int st[MAXN], ft[MAXN], add[MAXN];
int ans[MAXN];
int par[LG][MAXN];
vector<int> adj[MAXN];
vector<Q> node[MAXN];
int n, m;
int32_t main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cerr << "HELLO WORLD :)\n";
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int tmp;
    cin >> tmp;
    adj[tmp].push_back(i);
  }
  dfs(0);
  cin >> m;
  for (int i = 1; i <= m; i++) {
    int p, v;
    cin >> v >> p;
    node[get(v, p)].push_back({p, i});
  }
  sack(0, 0);
  for (int i = 1; i <= m; i++) cout << ans[i] << ' ';
  return cout << '\n', false;
}
void dfs(int v) {
  static int t = 0;
  st[v] = t++;
  add[st[v]] = v;
  for (int i = 1; i < LG; i++) par[i][v] = par[i - 1][par[i - 1][v]];
  for (auto u : adj[v]) {
    h[u] = h[v] + 1;
    par[0][u] = v;
    dfs(u);
  }
  ft[v] = t;
}
int get(int v, int p) {
  int u = v;
  for (int i = LG - 1; ~i; i--)
    if (p >> i & 1) u = par[i][u];
  return u;
}
void sack(int v, bool keep) {
  int id = -1, mx = -1;
  for (auto u : adj[v])
    if (smax(mx, ft[u] - st[u])) id = u;
  for (auto u : adj[v])
    if (u != id) sack(u, 0);
  if (id != -1) sack(id, 1);
  for (auto u : adj[v])
    if (u != id)
      for (int i = st[u]; i < ft[u]; i++) cnt[h[add[i]]]++;
  cnt[h[v]]++;
  if (v)
    for (auto u : node[v]) ans[u.id] = cnt[h[v] + u.p] - 1;
  if (!keep)
    for (int i = st[v]; i < ft[v]; i++) cnt[h[add[i]]]--;
}
