#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const long long N = 1e5 + 10;
const long long mod = 1e9 + 7;
const long long inf = -1e18;
const long long INF = 1e18;
long long bin_pow(long long n, long long k) {
  if (k == 0) return 1;
  if (k == 1) return n;
  if (n == 0) return 0;
  if (k % 2 == 0) {
    long long t = bin_pow(n, k / 2);
    return (t * t);
  } else {
    return (bin_pow(n, k - 1) * n);
  }
}
bool isprime(long long x) {
  if (x == 1) return false;
  if (x == 2 || x == 3 || x == 5 || x == 7) return true;
  if (x % 2 == 0 || x % 3 == 0 || x % 5 == 0 || x % 7 == 0) return false;
  for (int i = 2; i * i <= x; i++) {
    if (x % i == 0) return false;
  }
  return true;
}
long long phi(long long n) {
  long long result = n;
  for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      while (n % i == 0) n /= i;
      result -= result / i;
    }
  }
  if (n > 1) {
    result -= result / n;
  }
  return result;
}
int n, us[N], tin[N], tout[N], h[N], up[N][35], tim;
vector<int> vec[N], g[N];
void build_lca(int v) {
  us[v] = 1;
  tin[v] = ++tim;
  vec[h[v]].push_back(v);
  for (int i = 1; i <= 32; i++) {
    up[v][i] = up[up[v][i - 1]][i - 1];
  }
  for (int i = 0; i < g[v].size(); i++) {
    int to = g[v][i];
    if (us[to] == 0) {
      up[to][0] = v;
      h[to] = h[v] + 1;
      build_lca(to);
    }
  }
  tout[v] = ++tim;
}
int get_lca(int a, int b) {
  int pa = a, push_back = b;
  for (int i = 32; i >= 0; i--) {
    long long pw = bin_pow(2, i);
    if (pw <= b) {
      a = up[a][i];
      b -= pw;
      if (b == 0) break;
    }
  }
  if (a == 0 || b != 0) return -1;
  return a;
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  cin >> n;
  int x, y, q;
  for (int i = 1; i <= n; i++) {
    cin >> x;
    if (x != 0) {
      g[x].push_back(i);
    }
  }
  for (int i = 1; i <= n; i++) {
    if (us[i] == 0) {
      build_lca(i);
    }
  }
  cin >> q;
  for (int i = 1; i <= q; i++) {
    cin >> x >> y;
    int anc = get_lca(x, y);
    if (anc == -1) {
      cout << 0 << " ";
    } else {
      int l = 0, r = vec[h[x]].size() - 1;
      while (r - l > 1) {
        int mid = (r + l) >> 1;
        int to = vec[h[x]][mid];
        if (tin[to] < tin[anc]) {
          l = mid + 1;
        } else {
          r = mid;
        }
      }
      int to = vec[h[x]][l];
      if (tin[to] < tin[anc]) l++;
      int L = 0, R = vec[h[x]].size() - 1;
      while (R - L > 1) {
        int mid = (R + L) >> 1;
        int to = vec[h[x]][mid];
        if (tout[to] > tout[anc]) {
          R = mid - 1;
        } else {
          L = mid;
        }
      }
      to = vec[h[x]][R];
      if (tout[to] > tout[anc]) R--;
      cout << max(R - l, 0) << " ";
    }
  }
}
