#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) f = ch ^ 45, ch = getchar();
  while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
  return f ? x : -x;
}
int ls[100010 * 18], rs[100010 * 18], rt[100010];
int dep[100010], frt[100010], nxt[100010], v[100010];
set<int> t[100010 * 18];
map<string, int> ma;
int s[100010];
int n, m, maxd, cnt, tot, c;
int ans[100010], q[100010];
vector<int> vc[100010], ve[100010];
inline void add(int x, int y) {
  v[++tot] = y;
  nxt[tot] = frt[x];
  frt[x] = tot;
}
void getdep(int x) {
  maxd = max(maxd, dep[x]);
  for (int i = frt[x]; i; i = nxt[i]) {
    dep[v[i]] = dep[x] + 1;
    getdep(v[i]);
  }
}
inline int work(int x, int y) {
  if (t[x].size() < t[y].size()) x ^= y ^= x ^= y;
  for (set<int>::iterator it = t[y].begin(); it != t[y].end(); it++)
    t[x].insert(*it);
  return x;
}
void ins(int &now, int l, int r, int x, int k) {
  if (!now) now = ++cnt;
  if (l == r) {
    t[now].insert(s[k]);
    return;
  }
  int mid = l + r >> 1;
  if (x <= mid)
    ins(ls[now], l, mid, x, k);
  else
    ins(rs[now], mid + 1, r, x, k);
}
int merge(int x, int y, int l, int r) {
  if (!x || !y) return x ^ y;
  if (l == r) return work(x, y);
  int mid = l + r >> 1;
  ls[x] = merge(ls[x], ls[y], l, mid);
  rs[x] = merge(rs[x], rs[y], mid + 1, r);
  return x;
}
int query(int l, int r, int x, int now) {
  if (x > r) return 0;
  if (!now) return 0;
  if (l == r) {
    return t[now].size();
  }
  int mid = l + r >> 1;
  if (x <= mid)
    return query(l, mid, x, ls[now]);
  else
    return query(mid + 1, r, x, rs[now]);
}
void dfs(int x) {
  for (int i = frt[x]; i; i = nxt[i]) {
    dfs(v[i]);
    rt[x] = merge(rt[x], rt[v[i]], 1, maxd);
  }
  ins(rt[x], 1, maxd, dep[x], x);
  for (int i = 0; i < vc[x].size(); ++i)
    ans[ve[x][i]] = query(1, maxd, dep[x] + vc[x][i], rt[x]);
}
int main() {
  n = read();
  for (int i = 1; i <= n; ++i) {
    string str;
    cin >> str;
    if (!ma[str]) ma[str] = ++c;
    s[i] = ma[str];
    int x = read();
    add(x, i);
  }
  getdep(0);
  m = read();
  for (int i = 1; i <= m; ++i) {
    int x = read();
    ve[x].push_back(i);
    vc[x].push_back(read());
  }
  dfs(0);
  for (int i = 1; i <= m; ++i) cout << ans[i] << '\n';
}
