#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> conns;
vector<vector<pair<int, int>>> queries;
vector<vector<pair<int, int>>> resolvedQueries;
vector<int> results;
void resolveQueries(int pos, int prev, vector<int>& parents) {
  for (auto [dist, i] : queries[pos]) {
    if (dist <= parents.size()) {
      resolvedQueries[parents[parents.size() - dist]].emplace_back(dist, i);
    }
  }
  parents.push_back(pos);
  for (int p : conns[pos]) {
    if (p == prev) continue;
    resolveQueries(p, pos, parents);
  }
  parents.pop_back();
}
void fillResults(int pos, int prev, int depth, vector<int>& counts) {
  for (auto [dist, i] : resolvedQueries[pos]) {
    results[i] = -counts[depth + dist];
  }
  counts[depth]++;
  for (int p : conns[pos]) {
    if (p == prev) continue;
    fillResults(p, pos, depth + 1, counts);
  }
  for (auto [dist, i] : resolvedQueries[pos]) {
    results[i] += counts[depth + dist];
  }
}
int main() {
  int n, m;
  cin >> n;
  conns.resize(n);
  queries.resize(n);
  resolvedQueries.resize(n);
  vector<int> roots;
  for (int i = 0; i < n; i++) {
    int p;
    cin >> p;
    if (p > 0) {
      p--;
      conns[i].push_back(p);
      conns[p].push_back(i);
    } else {
      roots.push_back(i);
    }
  }
  cin >> m;
  results.resize(m);
  for (int i = 0; i < m; i++) {
    int pos, dist;
    cin >> pos >> dist;
    pos--;
    queries[pos].emplace_back(dist, i);
  }
  vector<int> counts(n);
  for (int r : roots) {
    vector<int> parents;
    resolveQueries(r, r, parents);
    fillResults(r, r, 0, counts);
  }
  for (int r : results) {
    cout << max(0, r - 1) << "\n";
  }
}
