#include <bits/stdc++.h>
using namespace std;
int n;
vector<vector<int>> adj;
int raiz, reloj, l;
vector<int> tin, tout, altura;
vector<vector<int>> tinDeAltura, up;
void leerGrafo() {
  cin >> n;
  adj.resize(n + 1);
  for (int i = 1; i <= n; ++i) {
    int r;
    cin >> r;
    adj[r].push_back(i);
  }
}
void dfs(int p, int a, int h) {
  tin[a] = reloj++;
  altura[a] = h;
  tinDeAltura[altura[a]].push_back(tin[a]);
  up[a][0] = p;
  for (int i = 1; i <= l; ++i) up[a][i] = up[up[a][i - 1]][i - 1];
  for (auto e : adj[a]) dfs(a, e, h + 1);
  tout[a] = reloj++;
}
void precomputo() {
  raiz = 0;
  reloj = 0;
  l = ceil(log2(n));
  tin.resize(n + 1);
  tout.resize(n + 1);
  altura.resize(n + 1);
  up.resize(n + 1, vector<int>(l + 1));
  tinDeAltura.resize(n + 1);
  dfs(raiz, raiz, 0);
}
int sube(int a, int n) {
  int mask = 0;
  while (n) {
    if (n & 1) a = up[a][mask];
    n >>= 1;
    ++mask;
  }
  return a;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  leerGrafo();
  precomputo();
  int m;
  cin >> m;
  while (m--) {
    int v, p;
    cin >> v >> p;
    if (p >= altura[v]) {
      cout << "0 ";
      continue;
    }
    v = sube(v, p);
    int ab = altura[v] + p;
    int L = (int)(upper_bound(tinDeAltura[ab].begin(), tinDeAltura[ab].end(),
                              tin[v]) -
                  tinDeAltura[ab].begin());
    int R = (int)(upper_bound(tinDeAltura[ab].begin(), tinDeAltura[ab].end(),
                              tout[v]) -
                  tinDeAltura[ab].begin());
    cout << R - L - 1 << " ";
  }
  cout << '\n';
  return 0;
}
