#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> graph[100005];
vector<int> nodesAtLevel[100005];
int rootVertex[100005];
int parent[100005];
int level[100005];
int ancestor[18][100005];
int dfsNumber;
int dfsBegin[100005];
int dfsEnd[100005];
void dfs(int u, int distance, int root) {
  dfsBegin[u] = ++dfsNumber;
  rootVertex[u] = root;
  level[u] = distance;
  nodesAtLevel[distance].push_back(u);
  for (auto v : graph[u]) {
    dfs(v, distance + 1, root);
  }
  dfsEnd[u] = dfsNumber;
}
void lcaPreprocess() {
  int i, j;
  for (i = 1; i <= n; i++) {
    ancestor[0][i] = parent[i];
  }
  for (j = 1; j <= 17; j++) {
    for (i = 1; i <= n; i++) {
      if (ancestor[j - 1] != 0) {
        ancestor[j][i] = ancestor[j - 1][ancestor[j - 1][i]];
      }
    }
  }
}
int getKthAncestor(int u, int k) {
  for (int j = 17; j >= 0; j--) {
    if (level[u] >= (1 << j) && (1 << j) <= k) {
      u = ancestor[j][u];
      k -= (1 << j);
    }
  }
  return (k == 0 ? u : -1);
}
int main() {
  int q, i, j, u, v, p, first, last, mid, firstIndex, lastIndex;
  scanf("%d", &n);
  for (v = 1; v <= n; v++) {
    scanf("%d", &u);
    parent[v] = u;
    if (u != 0) {
      graph[u].push_back(v);
    }
  }
  for (u = 1; u <= n; u++) {
    if (parent[u] == 0) {
      dfs(u, 0, u);
    }
  }
  lcaPreprocess();
  scanf("%d ", &q);
  while (q--) {
    scanf("%d %d", &v, &p);
    int ancestor = getKthAncestor(v, p);
    if (ancestor == -1) {
      cout << "0 ";
    } else {
      firstIndex = 0;
      lastIndex = 0;
      first = 0;
      last = nodesAtLevel[level[ancestor] + p].size() - 1;
      while (first <= last) {
        mid = (first + last) / 2;
        if (dfsBegin[ancestor] <=
                dfsBegin[nodesAtLevel[level[ancestor] + p][mid]] &&
            dfsBegin[nodesAtLevel[level[ancestor] + p][mid]] <=
                dfsEnd[ancestor]) {
          firstIndex = mid;
          last = mid - 1;
        } else if (dfsBegin[nodesAtLevel[level[ancestor] + p][mid]] >
                   dfsEnd[ancestor]) {
          last = mid - 1;
        } else {
          first = mid + 1;
        }
      }
      first = 0;
      last = nodesAtLevel[level[ancestor] + p].size() - 1;
      while (first <= last) {
        mid = (first + last) / 2;
        if (dfsBegin[ancestor] <=
                dfsBegin[nodesAtLevel[level[ancestor] + p][mid]] &&
            dfsBegin[nodesAtLevel[level[ancestor] + p][mid]] <=
                dfsEnd[ancestor]) {
          lastIndex = mid;
          first = mid + 1;
        } else if (dfsBegin[nodesAtLevel[level[ancestor] + p][mid]] >
                   dfsEnd[ancestor]) {
          last = mid - 1;
        } else {
          first = mid + 1;
        }
      }
      printf("%d ", (lastIndex - firstIndex + 1) - 1);
    }
  }
  return 0;
}
