#include <bits/stdc++.h>
using namespace std;
int mult(int x, int y) {
  long long int ans, x1 = (long long int)x, y1 = (long long int)y;
  ans = (x1 * y1) % 1000000007;
  return (int)ans;
}
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int lcm(int a, int b) { return a * (b / gcd(a, b)); }
long long int pow1(long long int a, long long int b) {
  long long int ans = 1;
  while (b > 0) {
    if (b & 1) ans = (ans * a) % 1000000007;
    a = (a * a) % 1000000007;
    b >>= 1;
  }
  return ans;
}
int mina(int arr[], int n) {
  int x = arr[0], i, pos = 0;
  for (i = 1; i < n; i++) {
    if (arr[i] < x) {
      x = arr[i];
      pos = i;
    }
  }
  return x;
}
int maxa(int arr[], int n) {
  int x = arr[0], i, pos = 0;
  for (i = 1; i < n; i++) {
    if (arr[i] > x) {
      x = arr[i];
      pos = i;
    }
  }
  return x;
}
int par[100005], f[100005], depth[100005], tmr, st[100005], en[100005],
    p[100005][21];
vector<vector<int> > v, level;
bool vis[100005];
void func(int n) {
  int i, j;
  for (i = 1; i < n + 1; i++) {
    for (j = 0; j <= 20; j++) p[i][j] = -1;
  }
  for (i = 1; i < n + 1; i++) p[i][0] = par[i];
  for (i = 1; i < n + 1; i++) {
    for (j = 1; j <= 20; j++) {
      if (p[i][j - 1] != -1) p[i][j] = p[p[i][j - 1]][j - 1];
    }
  }
}
void dfs(int u, int pr) {
  st[u] = tmr++;
  vis[u] = true;
  if (pr == -1) depth[u] = 0;
  par[u] = pr;
  level[depth[u]].push_back(st[u]);
  for (vector<int>::iterator itr = v[u].begin(); itr != v[u].end(); itr++) {
    int v1 = *itr;
    if (!vis[v1]) {
      depth[v1] = depth[u] + 1;
      dfs(v1, u);
    }
  }
  en[u] = tmr;
}
int findanc(int child, int h) {
  int ans = child, x = h, cnt = 0;
  while (x > 0) {
    int dig = (x % 2);
    if (dig == 1) ans = p[ans][cnt];
    cnt++;
    x /= 2;
  }
  return ans;
}
int quer(int node, int x) {
  int start = st[node], enda = en[node];
  return upper_bound(level[depth[node] + x].begin(),
                     level[depth[node] + x].end(), enda) -
         lower_bound(level[depth[node] + x].begin(),
                     level[depth[node] + x].end(), start);
}
int main() {
  int m, n, i, j, k;
  scanf("%d", &n);
  v.resize(n + 2);
  level.resize(n + 2);
  for (i = 1; i < n + 1; i++) {
    int x;
    scanf("%d", &x);
    if (x)
      v[x].push_back(i);
    else
      f[i] = 1;
  }
  for (i = 1; i < n + 1; i++) {
    if (f[i]) dfs(i, -1);
  }
  func(n);
  for (i = 0; i < n + 2; i++) sort(level[i].begin(), level[i].end());
  scanf("%d", &m);
  int v1, p1;
  for (i = 0; i < m; i++) {
    scanf("%d", &v1);
    scanf("%d", &p1);
    if (depth[v1] < p1)
      cout << "0 ";
    else {
      int anc = findanc(v1, p1);
      cout << quer(anc, p1) - 1 << " ";
    }
  }
  cout << endl;
  return 0;
}
