#include <bits/stdc++.h>
using namespace std;
const int N = 100008;
map<string, int> f;
unordered_map<int, int> b[N];
vector<int> a[N];
vector<pair<int, int> > que[N];
int n, m, nam[N], tot, ans[N], dep[N], siz[N], son[N], st[N], ed[N], id[N],
    cot[N + N];
int dfs(int x) {
  id[st[x] = ++tot] = x;
  siz[x] = 1;
  int pp = 0;
  for (auto p : a[x]) {
    dep[p] = dep[x] + 1;
    dfs(p);
    siz[x] += siz[p];
    if (siz[p] > pp) {
      pp = siz[p];
      son[x] = p;
    }
  }
  ed[x] = tot;
  return 0;
}
int dfsx(int x, int keep) {
  for (auto p : a[x])
    if (p != son[x]) dfsx(p, 0);
  if (son[x]) dfsx(son[x], 1);
  if (x) {
    for (auto p : a[x])
      if (p != son[x])
        for (int q = st[p]; q <= ed[p]; q++) {
          if (1 == ++b[dep[id[q]]][nam[id[q]]]) cot[dep[id[q]]]++;
        }
    if (1 == ++b[dep[x]][nam[x]]) cot[dep[x]]++;
    for (auto p : que[x]) ans[p.second] = cot[p.first];
  }
  if (keep == 0)
    for (int p = st[x]; p <= ed[x]; p++) {
      if (0 == --b[dep[id[p]]][nam[id[p]]]) cot[dep[id[p]]]--;
    }
  return 0;
}
int main(void) {
  std::ios::sync_with_stdio(false);
  int i, k, p1, p2;
  string str;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> str >> k;
    a[k].push_back(i);
    if (f.find(str) == f.end())
      f[str] = nam[i] = ++tot;
    else
      nam[i] = f[str];
  }
  cin >> m;
  tot = 0;
  dep[0] = 0;
  dfs(0);
  for (i = 1; i <= m; i++) {
    cin >> p1 >> p2;
    que[p1].push_back(make_pair(dep[p1] + p2, i));
  }
  dfsx(0, 0);
  for (i = 1; i <= m; i++) cout << ans[i] << endl;
  return 0;
}
