#include <bits/stdc++.h>
using namespace std;
inline long long labs(long long a) { return a < 0 ? (-a) : a; }
template <typename T>
inline T sqr(T x) {
  return x * x;
}
struct Node {
  int deep;
  int p;
  vector<int> to;
  int tin, tout;
};
const int MAXN = 100005;
vector<pair<int, int> > mas[MAXN];
vector<Node> g;
int n;
int t = 0;
void DFS(int i, int deep = 0) {
  g[i].deep = deep;
  g[i].tin = t++;
  mas[deep].push_back(make_pair(g[i].tin, i));
  for (int(j) = 0; (j) < (g[i].to.size()); (j)++) {
    int to = g[i].to[j];
    DFS(to, deep + 1);
  }
  g[i].tout = t++;
}
int main() {
  cin >> n;
  n++;
  g.resize(n);
  for (int(i) = 0; (i) < (n - 1); (i)++) {
    cin >> g[i + 1].p;
    g[g[i + 1].p].to.push_back(i + 1);
  }
  DFS(0);
  int m;
  cin >> m;
  for (int(qqq) = 0; (qqq) < (m); (qqq)++) {
    int i, ppp;
    cin >> i >> ppp;
    int pd = g[i].deep - ppp;
    if (pd <= 0) {
      cout << 0 << " ";
      continue;
    }
    int pit = upper_bound((mas[pd]).begin(), (mas[pd]).end(),
                          make_pair(g[i].tin, 0)) -
              mas[pd].begin() - 1;
    int p = mas[pd][pit].second;
    int ubl = upper_bound((mas[g[i].deep]).begin(), (mas[g[i].deep]).end(),
                          make_pair(g[p].tin, 0)) -
              mas[g[i].deep].begin();
    int ubr = upper_bound((mas[g[i].deep]).begin(), (mas[g[i].deep]).end(),
                          make_pair(g[p].tout, 0)) -
              mas[g[i].deep].begin() - 1;
    cout << ubr - ubl << " ";
  }
  cout << endl;
  return 0;
}
