#include <bits/stdc++.h>
using namespace std;
const int M = 100010;
int n, m;
int fa[M], root[M];
template <typename T>
inline void read(T &x) {
  x = 0;
  char ch = getchar();
  int f = 1;
  for (; ch < '0' || ch > '9'; ch = getchar())
    if (ch == '-') f = -1;
  for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
  x *= f;
}
vector<int> v[M];
vector<pair<int, int> > query[M];
struct Query {
  int dep_f, dep_p, id;
  inline bool operator<(const Query &x) const { return dep_f < x.dep_f; }
};
priority_queue<Query> q;
namespace tr {
int tr[M << 6], ls[M << 6], rs[M << 6], cnt = 0;
void insert(int &pos, int l, int r, int val) {
  if (!pos) pos = ++cnt;
  if (l == r) return (void)(tr[pos]++);
  int mid = l + r >> 1;
  if (val <= mid)
    insert(ls[pos], l, mid, val);
  else
    insert(rs[pos], mid + 1, r, val);
}
int query(int pos, int l, int r, int x) {
  if (!pos) return 0;
  if (l == r) return tr[pos];
  int mid = l + r >> 1;
  if (x <= mid)
    return query(ls[pos], l, mid, x);
  else
    return query(rs[pos], mid + 1, r, x);
}
int merge(int a, int b, int l, int r) {
  if (!a || !b) return a + b;
  if (l == r) return tr[a] += tr[b], a;
  int mid = l + r >> 1;
  ls[a] = merge(ls[a], ls[b], l, mid);
  rs[a] = merge(rs[a], rs[b], mid + 1, r);
  return a;
}
}  // namespace tr
int dep[M], ans[M];
void dfs(int pos) {
  for (int i = 0; i < (int)v[pos].size(); i++) {
    dep[v[pos][i]] = dep[pos] + 1;
    dfs(v[pos][i]);
    tr::merge(root[pos], root[v[pos][i]], 1, n);
  }
  while (!q.empty() && q.top().dep_f == dep[pos]) {
    int son = q.top().dep_p, id = q.top().id;
    q.pop();
    ans[id] = tr::query(root[pos], 1, n, son) - 1;
  }
  tr::insert(root[pos], 1, n, dep[pos]);
  for (int i = 0; i < (int)query[pos].size(); i++)
    if (dep[pos] > query[pos][i].first)
      q.push((Query){dep[pos] - query[pos][i].first, dep[pos],
                     query[pos][i].second});
}
int main() {
  read(n);
  tr::cnt = n;
  for (int i = 1; i <= n; i++) {
    read(fa[i]);
    root[i] = i;
    if (fa[i]) v[fa[i]].push_back(i);
  }
  read(m);
  for (int i = 1, x, y; i <= m; i++)
    read(x), read(y), query[x].push_back(make_pair(y, i));
  for (int i = 1; i <= n; i++)
    if (!dep[i]) dep[i] = 1, dfs(i);
  for (int i = 1; i <= m; i++) printf("%d ", ans[i]);
  return 0;
}
