#include <bits/stdc++.h>
using namespace std;
void dfs(int, int);
const int MAX_N = 100 * 1000 + 10;
int n, q, q_p[MAX_N], q_h[MAX_N], ans[MAX_N];
vector<int> root, adj[MAX_N], tmp_list[MAX_N], q_list[MAX_N], path;
map<int, int> mp[MAX_N];
void read_jungle() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    int par;
    cin >> par;
    par--;
    if (par == -1)
      root.push_back(i);
    else
      adj[par].push_back(i);
  }
}
void read_queries() {
  cin >> q;
  for (int i = 0; i < q; i++) {
    int v;
    cin >> v >> q_p[i];
    v--;
    tmp_list[v].push_back(i);
  }
}
void read_input() {
  read_jungle();
  read_queries();
}
void fill_q_list(int v, int cur_h) {
  for (int i : tmp_list[v]) {
    q_h[i] = cur_h;
    int p = q_p[i];
    if ((int)path.size() >= p) q_list[path[(int)path.size() - p]].push_back(i);
  }
}
void dfs0(int v, int cur_h = 0) {
  fill_q_list(v, cur_h);
  path.push_back(v);
  for (int u : adj[v]) dfs0(u, cur_h + 1);
  path.pop_back();
}
void go_to_childs(int v, int cur_h) {
  mp[v][cur_h]++;
  for (int u : adj[v]) {
    dfs(u, cur_h + 1);
    if (mp[u].size() > mp[v].size()) swap(mp[u], mp[v]);
  }
}
void update_mp(int v) {
  for (int u : adj[v])
    for (auto i : mp[u]) {
      int h = i.first;
      int cnt = i.second;
      mp[v][h] += cnt;
    }
}
void fill_ans(int v) {
  for (int i : q_list[v]) {
    int h = q_h[i];
    ans[i] = mp[v][h] - 1;
  }
}
void dfs(int v, int cur_h = 0) {
  go_to_childs(v, cur_h);
  update_mp(v);
  fill_ans(v);
}
void solve() {
  for (int r : root) dfs0(r);
  for (int r : root) dfs(r);
}
void print_output() {
  for (int i = 0; i < q; i++) cout << ans[i] << ' ';
}
int main() {
  ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  read_input();
  solve();
  print_output();
}
