#include <bits/stdc++.h>
using namespace std;
const int ms = 1e5 + 5, mlg = 23;
int par[ms][mlg + 1], lvl[ms], n;
int id = 1;
vector<int> g[ms];
vector<int> h[ms];
int in[ms], out[ms];
void dfs(int v, int p, int l = 0) {
  lvl[v] = l;
  in[v] = id++;
  h[l].push_back(id);
  par[v][0] = p;
  for (int k = 1; k <= mlg; ++k) {
    par[v][k] = par[par[v][k - 1]][k - 1];
  }
  for (int u : g[v]) {
    if (u != p) {
      dfs(u, v, l + 1);
    }
  }
  out[v] = id++;
}
int up(int a, int p) {
  for (int i = mlg; i >= 0; --i) {
    if (p & (1 << i)) {
      a = par[a][i];
    }
  }
  return a;
}
int main() {
  cin >> n;
  vector<int> root;
  for (int i = 0; i < n; ++i) {
    int x;
    scanf("%d", &x);
    if (x == 0) {
      root.push_back(i);
    } else {
      g[x - 1].push_back(i);
    }
  }
  for (int i = 0; i < root.size(); ++i) {
    dfs(root[i], root[i]);
  }
  int m;
  cin >> m;
  while (m--) {
    int v, p;
    scanf("%d%d", &v, &p);
    v--;
    if (lvl[v] < p) {
      cout << "0 ";
    } else {
      int parent = up(v, p);
      int ans = upper_bound(h[lvl[v]].begin(), h[lvl[v]].end(), out[parent]) -
                lower_bound(h[lvl[v]].begin(), h[lvl[v]].end(), in[parent]);
      ans--;
      cout << ans << ' ';
    }
  }
  return 0;
}
