#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
inline bool EQ(double a, double b) { return fabs(a - b) < 1e-9; }
long long add(long long a, long long b) {
  long long ret = a + b;
  if (ret >= 1000000007) ret -= 1000000007;
  return ret;
}
long long subtract(long long a, long long b) {
  long long ret = a - b;
  if (ret < 0) ret += 1000000007;
  return ret;
}
long long mult(long long a, long long b) {
  long long ret = a * b;
  if (ret >= 1000000007) ret %= 1000000007;
  return ret;
}
long long bigmod(long long a, long long b) {
  long long ret = 1;
  while (b) {
    if (b & 1) ret = mult(ret, a);
    b >>= 1;
    a = mult(a, a);
  }
  return ret;
}
long long inverse(long long n) { return bigmod(n, 1000000007 - 2); }
bool base[1000010];
vector<int> primes;
void sieve(int mx) {
  mx += 10;
  int x = sqrt(mx);
  for (int i = 3; i <= x; i += 2)
    if (base[i] == 0)
      for (int j = i * i, k = i << 1; j < mx; j += k) base[j] = 1;
  primes.push_back(2);
  for (int i = 3; i < mx; i += 2)
    if (base[i] == 0) primes.push_back(i);
}
int setBit(int n, int i) { return (n | (1 << i)); }
int resetBit(int n, int i) { return (n & (~(1 << i))); }
int sub[100010], parent[100010][22], cnt[100010], big[100010], ans[100010],
    lev[100010];
vector<int> e[100010];
vector<pair<int, int> > q[100010];
void fs(int u, int d) {
  sub[u] = 1;
  lev[u] = d;
  for (int &v : e[u]) {
    fs(v, d + 1);
    parent[v][0] = u;
    sub[u] += sub[v];
  }
}
void add(int u, int x) {
  cnt[lev[u]] += x;
  for (int &v : e[u])
    if (!big[v]) {
      add(v, x);
    }
}
void dfs(int u, int keep) {
  int mx = -1, bigchild = -1;
  for (int &v : e[u])
    if (sub[v] > mx) {
      mx = sub[v], bigchild = v;
    }
  for (int &v : e[u])
    if (v != bigchild) {
      dfs(v, 0);
    }
  if (bigchild != -1) {
    dfs(bigchild, 1);
    big[bigchild] = 1;
  }
  add(u, 1);
  for (pair<int, int> &it : q[u]) ans[it.second] = cnt[it.first + lev[u]] - 1;
  if (bigchild != -1) {
    big[bigchild] = 0;
  }
  if (!keep) {
    add(u, -1);
  }
}
int main() {
  int n, Q, u, h, x;
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &x);
    e[x].push_back(i);
  }
  for (int i = 0; i < n + 1; ++i)
    for (int j = 0; j < 18; ++j) parent[i][j] = -1;
  fs(0, -1);
  for (int j = 1; (1 << j) <= n; ++j)
    for (int i = 1; i <= n; ++i) {
      if (parent[i][j - 1] != -1)
        parent[i][j] = parent[parent[i][j - 1]][j - 1];
    }
  scanf("%d", &Q);
  for (int i = 0; i < Q; ++i) {
    scanf("%d%d", &u, &h);
    for (int j = 17; j >= 0; --j)
      if ((bool)((h) & (1 << (j)))) {
        u = parent[u][j];
      }
    if (u) q[u].push_back({h, i});
  }
  dfs(0, 0);
  for (int i = 0; i < Q; ++i) printf("%d ", ans[i]);
  puts("");
  return 0;
}
