#include <bits/stdc++.h>
int const maxn = 1e5 + 10;
int const maxm = 1e5 + 10;
using namespace std;
unordered_map<int, int> cnt[maxn];
unordered_map<string, int> p;
int id[maxn];
int idx = 0;
vector<pair<int, int> > query[maxn];
int ans[maxn];
int head[maxn], tot;
struct Edg {
  int to, next;
} edg[maxm * 2];
void inint() {
  memset(head, -1, sizeof head);
  tot = 0;
}
void add(int u, int v) {
  edg[tot].next = head[u];
  edg[tot].to = v;
  head[u] = tot++;
}
int dep[maxn], son[maxn], sz[maxn];
void dfs1(int x, int fa) {
  sz[x] = 1;
  int maxval = 0;
  for (int i = head[x]; ~i; i = edg[i].next) {
    int y = edg[i].to;
    dep[y] = dep[x] + 1;
    dfs1(y, x);
    sz[x] += sz[y];
    if (sz[y] > maxval) {
      maxval = sz[y];
      son[x] = y;
    }
  }
}
void erase(int x, int fa) {
  cnt[dep[x]][id[x]]--;
  if (cnt[dep[x]][id[x]] == 0) cnt[dep[x]].erase(id[x]);
  for (int i = head[x]; ~i; i = edg[i].next) {
    int y = edg[i].to;
    erase(y, x);
  }
}
void get(int x, int fa, int p) {
  cnt[dep[x]][id[x]]++;
  for (int i = head[x]; ~i; i = edg[i].next) {
    int y = edg[i].to;
    if (y == p) continue;
    get(y, x, p);
  }
}
void dfs(int x, int fa) {
  for (int i = head[x]; ~i; i = edg[i].next) {
    int y = edg[i].to;
    if (y == son[x]) continue;
    dfs(y, x);
    erase(y, x);
  }
  if (son[x]) dfs(son[x], x);
  get(x, fa, son[x]);
  for (auto now : query[x]) {
    ans[now.first] = cnt[now.second].size();
  }
}
int main() {
  int n;
  scanf("%d", &n);
  string ch;
  int pre;
  inint();
  for (int i = 1; i <= n; i++) {
    cin >> ch;
    if (p.count(ch) == 0) {
      p[ch] = ++idx;
    }
    id[i] = p[ch];
    scanf("%d", &pre);
    add(pre, i);
  }
  int m;
  scanf("%d", &m);
  dfs1(0, -1);
  for (int i = 1; i <= m; i++) {
    int v, k;
    scanf("%d%d", &v, &k);
    if (dep[v] + k > 1e5) {
      ans[i] = 0;
      continue;
    }
    query[v].push_back({i, dep[v] + k});
  }
  dfs(0, -1);
  for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
  return 0;
}
