#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
int to[MAXN << 1], nxt[MAXN << 1], head[MAXN];
int cnte;
int v[MAXN], ans[MAXN];
int N, Q, id;
vector<pair<int, int>> Qr[MAXN];
inline void addedge(int x, int y) {
  to[++cnte] = y;
  nxt[cnte] = head[x];
  head[x] = cnte;
}
struct DSU {
  int sz[MAXN], dep[MAXN], son[MAXN], Sz[MAXN];
  int Son;
  map<int, int> cnt[MAXN];
  inline void Init() { memset(son, -1, sizeof(son)); }
  inline void dfs1(int x, int fth) {
    sz[x] = 1;
    dep[x] = dep[fth] + 1;
    for (int i = head[x]; i; i = nxt[i]) {
      int y = to[i];
      if (y != fth) {
        dfs1(y, x);
        sz[x] += sz[y];
        if (son[x] == -1 || sz[y] > sz[son[x]]) son[x] = y;
      }
    }
  }
  inline void add(int x, int fth, int flg) {
    if (flg == 1) {
      cnt[dep[x]][v[x]]++;
      if (cnt[dep[x]][v[x]] == 1) Sz[dep[x]]++;
    } else {
      cnt[dep[x]][v[x]]--;
      if (!cnt[dep[x]][v[x]]) Sz[dep[x]]--;
    }
    for (int i = head[x]; i; i = nxt[i]) {
      int y = to[i];
      if (y != fth && y != Son) add(y, x, flg);
    }
  }
  inline void dfs2(int x, int fth, int opt) {
    for (int i = head[x]; i; i = nxt[i]) {
      int y = to[i];
      if (y != fth && y != son[x]) dfs2(y, x, 0);
    }
    if (son[x] != -1) {
      dfs2(son[x], x, 1);
      Son = son[x];
    } else
      Son = -1;
    add(x, fth, 1);
    Son = -1;
    for (auto now : Qr[x]) {
      int k = now.first, id = now.second;
      if (dep[x] + k >= MAXN)
        ans[id] = 0;
      else
        ans[id] = (int)Sz[dep[x] + k];
    }
    if (!opt) add(x, fth, -1);
  }
} dsu;
map<string, int> dfn;
string S;
int main() {
  ios::sync_with_stdio(false);
  cin >> N;
  for (int i = 1; i <= N; i++) {
    int fa;
    cin >> S;
    cin >> fa;
    if (!dfn[S]) dfn[S] = ++id;
    v[i] = dfn[S];
    addedge(fa, i);
  }
  cin >> Q;
  for (int i = 1; i <= Q; i++) {
    int x, k;
    cin >> x >> k;
    Qr[x].push_back({k, i});
  }
  dsu.Init();
  dsu.dfs1(0, 0);
  dsu.dfs2(0, 0, 0);
  for (int i = 1; i <= Q; i++) cout << ans[i] << '\n';
  return 0;
}
