#include <bits/stdc++.h>
using namespace std;
inline int in() {
  int32_t x;
  scanf("%d", &x);
  return x;
}
inline string get() {
  char ch[100];
  scanf("%s", ch);
  return ch;
}
const int MAX_LG = 21;
const int maxn = 5e5 + 10;
const int mod = 1e9 + 7;
int root;
vector<int> g[maxn];
vector<pair<int, int> > g2[maxn];
vector<pair<string, int> > vc;
int cmp[maxn], sz[maxn], lvl[maxn], res[maxn];
bool mark[maxn];
map<int, int> cnt[maxn];
int cnt2[maxn];
inline void calc(int v) {
  sz[v] = 1;
  for (auto u : g[v]) lvl[u] = lvl[v] + 1, calc(u), sz[v] += sz[u];
}
inline void add(int v, int val) {
  if ((cnt[lvl[v]][cmp[v]] == 1 && val == -1) ||
      (cnt[lvl[v]][cmp[v]] == 0 && val == 1))
    cnt2[lvl[v]] += val;
  cnt[lvl[v]][cmp[v]] += val;
  for (auto u : g[v])
    if (!mark[u]) add(u, val);
}
inline void dfs(int v, int del = 1) {
  int maxi = -1, id = -1;
  for (auto u : g[v])
    if (sz[u] > maxi) maxi = sz[u], id = u;
  for (auto u : g[v])
    if (u - id) dfs(u);
  if (id + 1) dfs(id, 0), mark[id] = true;
  add(v, 1);
  for (int i = 0; i < g2[v].size(); i++)
    res[g2[v][i].second] = cnt2[g2[v][i].first];
  if (id + 1) mark[id] = false;
  if (del) add(v, -1);
}
int32_t main() {
  int n = in();
  root = 0;
  for (int i = 0; i < n; i++) {
    string name = get();
    int parent = in();
    g[parent].push_back(i + 1);
    vc.push_back({name, i + 1});
  }
  sort(vc.begin(), vc.end());
  for (int i = 0; i < vc.size(); i++)
    cmp[vc[i].second] =
        (i && vc[i].first == vc[i - 1].first ? cmp[vc[i - 1].second] : i);
  int m = in();
  calc(root);
  for (int i = 0; i < m; i++) {
    int v = in(), h = lvl[v] + in();
    g2[v].push_back({h, i});
  }
  dfs(root);
  for (int i = 0; i < m; i++) printf("%d\n", res[i]);
}
