#include <bits/stdc++.h>
using namespace std;
const int n = 100000;
class sp {
 public:
  int q;
  sp *w;
  sp(int q1, sp *w1) {
    q = q1;
    w = w1;
  }
};
sp *a[n];
int q, i = 0, s[n], s1[n], s2[n], h[n];
void qs(int q, int w) {
  int e = q, r = w, t = h[q + (rand() % (w - q + 1))], y;
  do {
    while ((s2[h[e]] < s2[t]) || ((s2[h[e]] == s2[t]) && (s[h[e]] < s[t]))) e++;
    while ((s2[h[r]] > s2[t]) || ((s2[h[r]] == s2[t]) && (s[h[r]] > s[t]))) r--;
    if (e <= r) {
      y = h[e];
      h[e] = h[r];
      h[r] = y;
      e++;
      r--;
    }
  } while (e <= r);
  if (q < r) qs(q, r);
  if (e < w) qs(e, w);
}
void in(int q, int t) {
  s[q] = i;
  i++;
  s2[q] = t;
  t++;
  for (sp *c = a[q]; c; c = c->w) in(c->q, t);
  s1[q] = i;
}
int bp(int w, int e) {
  int r = -1, c, v;
  for (v = 1 << 16; v; v >>= 1) {
    c = r + v;
    if ((c < q) && ((s2[h[c]] < w) || ((s2[h[c]] == w) && (s[h[c]] <= e))))
      r = c;
  }
  return r;
}
int main() {
  int w, e, r, t, c, v;
  scanf("%d", &q);
  for (w = 0; w < q; w++) {
    a[w] = 0;
    s[w] = 1;
  }
  for (w = 0; w < q; w++) {
    h[w] = w;
    scanf("%d", &e);
    if (e)
      a[e - 1] = new sp(w, a[e - 1]);
    else
      s[w] = 0;
  }
  for (w = 0; w < q; w++)
    if (!s[w]) in(w, 0);
  qs(0, q - 1);
  for (scanf("%d", &w); w; w--) {
    scanf("%d%d", &e, &r);
    e--;
    if (s2[e] < r) {
      printf("0 ");
      continue;
    }
    c = h[bp(s2[e] - r, s[e])];
    c = bp(s2[c] + r, s1[c] - 1) - bp(s2[c] + r, s[c] - 1);
    printf("%d ", c - 1);
  }
  return 0;
}
