#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (a == 0) return b;
  return gcd(b, a % b);
}
long long lcm(long long a, long long b) { return (a / gcd(a, b)) * b; }
int n, cnt[100005], subsize[100005], depth[100005], ans[100005];
bool big[100005];
vector<int> adj[100005];
vector<pair<int, int> > qarr[100005];
void dfs0(int v, int d) {
  subsize[v] = 1;
  depth[v] = d;
  for (int i = 0; i < (int)adj[v].size(); i++) {
    int vv = adj[v][i];
    dfs0(vv, d + 1);
    subsize[v] += subsize[vv];
  }
}
void add(int v) {
  cnt[depth[v]]++;
  for (int i = 0; i < (int)adj[v].size(); i++) {
    int vv = adj[v][i];
    if (big[vv]) continue;
    add(vv);
  }
}
void remove(int v) {
  cnt[depth[v]]--;
  for (int i = 0; i < (int)adj[v].size(); i++) {
    int vv = adj[v][i];
    if (big[vv]) continue;
    remove(vv);
  }
}
void dfs(int v, bool heavy_edge) {
  int heavy_child = -1;
  for (int i = 0; i < (int)adj[v].size(); i++) {
    int vv = adj[v][i];
    if (heavy_child == -1 || subsize[vv] > subsize[heavy_child])
      heavy_child = vv;
  }
  for (int i = 0; i < (int)adj[v].size(); i++) {
    int vv = adj[v][i];
    if (vv == heavy_child) continue;
    dfs(vv, false);
  }
  if (heavy_child != -1) {
    dfs(heavy_child, true);
    big[heavy_child] = true;
  }
  add(v);
  for (int i = 0; i < (int)qarr[v].size(); i++) {
    int k = qarr[v][i].first, idx = qarr[v][i].second;
    ans[idx] = cnt[depth[v] + k] - 1;
  }
  if (heavy_child != -1) {
    big[heavy_child] = false;
  }
  if (!heavy_edge) {
    remove(v);
  }
}
void clear_val(int v) {
  cnt[depth[v]] = 0;
  for (int i = 0; i < (int)adj[v].size(); i++) {
    int vv = adj[v][i];
    clear_val(vv);
  }
}
vector<int> roots;
int par[20][100005];
int kth_ancestor(int v, int k) {
  for (int i = 19; i >= 0; i--)
    if ((k >> i) & 1) v = par[i][v];
  return v;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n;
  memset(par, -1, sizeof(par));
  for (int i = 1; i <= n; i++) {
    cin >> par[0][i];
    if (par[0][i] == 0) {
      roots.push_back(i);
      par[0][i] = -1;
    } else
      adj[par[0][i]].push_back(i);
  }
  for (int j = 0; j < 19; j++)
    for (int i = 1; i <= n; i++)
      if (par[j][i] != -1) par[j + 1][i] = par[j][par[j][i]];
  for (int i = 0; i < (int)roots.size(); i++) {
    dfs0(roots[i], 0);
  }
  int q;
  cin >> q;
  for (int i = 1; i <= q; i++) {
    int v, k;
    cin >> v >> k;
    if (k > depth[v]) continue;
    qarr[kth_ancestor(v, k)].push_back(pair<int, int>(k, i));
  }
  for (int i = 0; i < (int)roots.size(); i++) {
    dfs(roots[i], true);
    clear_val(roots[i]);
  }
  for (int i = 1; i <= q; i++) cout << ans[i] << " ";
  return 0;
}
