#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void Cin(T& x) {
  char c;
  T sign = 1;
  x = 0;
  for (c = getchar(); c < '0' || c > '9'; c = getchar())
    if (c == '-') sign = -1;
  for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - '0';
  x *= sign;
}
const int N = 1e6 + 7;
const int M = 1e5 + 7;
const int logN = 22;
int sz[N], n, m, v, p, res[N], cnt[N], h[N], par[N][logN];
vector<int> a[N], z;
vector<pair<int, int> > q[N];
bool big[N];
void Build_sz(int u) {
  sz[u] = 1;
  for (int v : a[u]) {
    h[v] = h[u] + 1;
    Build_sz(v);
    sz[u] += sz[v];
  }
}
void Add(int u, int count) {
  cnt[h[u]] += count;
  for (int v : a[u]) {
    if (big[v]) continue;
    Add(v, count);
  }
}
void DFS(int u, bool keep) {
  int b = -1;
  for (int v : a[u])
    if (b == -1 || sz[b] < sz[v]) b = v;
  for (int v : a[u])
    if (v != b) DFS(v, 0);
  if (b != -1) big[b] = 1, DFS(b, 1);
  Add(u, 1);
  for (pair<int, int>& adj : q[u]) res[adj.second] = cnt[adj.first] - 1;
  if (b != -1) big[b] = 0;
  if (!keep) Add(u, -1);
}
int LCA(int u, int p) {
  int log = log2(h[u]);
  for (int i = log; i >= 0; --i) {
    if (h[u] - (1 << i) >= p) u = par[u][i];
  }
  return u;
}
void Enter() {
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> par[i][0];
    if (par[i][0])
      a[par[i][0]].push_back(i);
    else
      z.push_back(i), h[i] = 1;
  }
}
void Solve() {
  for (int u : z) Build_sz(u);
  for (int j = 1; j <= logN - 1; ++j) {
    for (int i = 1; i <= n; ++i) par[i][j] = par[par[i][j - 1]][j - 1];
  }
  cin >> m;
  for (int i = 1; i <= m; ++i) {
    cin >> v >> p;
    if (p >= h[v])
      res[i] = 0;
    else {
      int u = LCA(v, h[v] - p);
      q[u].push_back({h[v], i});
    }
  }
  for (int u : z) DFS(u, 0);
  for (int i = 1; i <= m; ++i) cout << res[i] << ' ';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  Enter();
  Solve();
  return 0;
}
