#include <bits/stdc++.h>
inline int sbt(int x) { return __builtin_popcount(x); }
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
  cout << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
  const char* comma = strchr(names + 1, ',');
  cout.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
vector<int> adj[100013];
int par[100013][33];
vector<int> dfslevel[100013];
int start[100013];
int endt[100013];
int lev[100013];
int n, k;
int timer = 0;
void dfs(int node, int p, int level) {
  start[node] = timer;
  timer++;
  lev[node] = level;
  dfslevel[level].push_back(start[node]);
  par[node][0] = p;
  for (auto nei : adj[node]) {
    if (nei != p) {
      dfs(nei, node, level + 1);
    }
  }
  endt[node] = timer;
  timer++;
}
int f(int node) {
  int curr = node;
  for (int i = 33 - 1; i >= 0; i--) {
    if (k & (1ll << i)) {
      curr = par[curr][i];
    }
  }
  return curr;
}
int main() {
  cin.sync_with_stdio(false);
  cout.sync_with_stdio(false);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int x;
    cin >> x;
    adj[x].push_back(i);
    adj[i].push_back(x);
  }
  dfs(0, -1, 0);
  for (int i = 1; i < 33; i++) {
    for (int node = 1; node <= n; node++) {
      par[node][i] = par[par[node][i - 1]][i - 1];
    }
  }
  int q;
  cin >> q;
  while (q--) {
    int u;
    cin >> u >> k;
    int node_level = lev[u];
    int target = f(u);
    if (target <= 0) {
      cout << 0 << ' ';
      continue;
    }
    int shuru = start[target];
    int khatam = endt[target];
    int same_lev = (lower_bound(dfslevel[node_level].begin(),
                                dfslevel[node_level].end(), khatam) -
                    lower_bound(dfslevel[node_level].begin(),
                                dfslevel[node_level].end(), shuru)) -
                   1;
    cout << same_lev << ' ';
  }
  return 0;
}
