#include <bits/stdc++.h>
using namespace std;
int BC[200005], sz[200005], res[200005], n, m, clr[200005], cnt[200005];
bool mark[200005];
multiset<int> s[200005];
map<string, int> mp;
vector<int> graph[200005];
vector<int> par;
vector<pair<int, int> > qur[200005];
multiset<int>::iterator it;
void getsz(int u, int p) {
  int best = -1;
  BC[u] = -1;
  sz[u] = 1;
  int len = graph[u].size();
  for (int i = 0; i < len; i++) {
    int v = graph[u][i];
    if (v == p) continue;
    getsz(v, u);
    sz[u] += sz[v];
    if (sz[v] > best) {
      best = sz[v];
      BC[u] = v;
    }
  }
}
void add(int u, int p, int level, int x) {
  if (x == 1) {
    if (s[level].find(clr[u]) == s[level].end()) cnt[level]++;
    s[level].insert(clr[u]);
  }
  if (x == -1) {
    it = s[level].find(clr[u]);
    if (it != s[level].end()) {
      s[level].erase(it);
      if (s[level].find(clr[u]) == s[level].end()) cnt[level]--;
    }
  }
  int len = graph[u].size();
  for (int i = 0; i < len; i++) {
    int v = graph[u][i];
    if (v != p and mark[v] == 0) add(v, u, level + 1, x);
  }
}
void dfs(int u, int p, int level, int clean) {
  int len = graph[u].size();
  for (int i = 0; i < len; i++) {
    int v = graph[u][i];
    if (v != p and BC[u] != v) dfs(v, u, level + 1, 0);
  }
  if (BC[u] != -1) {
    dfs(BC[u], u, level + 1, 1);
    mark[BC[u]] = 1;
  }
  add(u, p, level, 1);
  int len1 = qur[u].size();
  for (int i = 0; i < len1; i++) {
    pair<int, int> temp = qur[u][i];
    res[temp.second] = cnt[level + temp.first];
  }
  if (BC[u] != -1) mark[BC[u]] = 0;
  if (clean == 0) {
    add(u, p, level, -1);
  }
}
int main() {
  string str;
  cin >> n;
  int k = 0;
  for (int i = 0; i < n; i++) {
    int p;
    cin >> str >> p;
    if (!mp[str]) {
      k++;
      mp[str] = k;
    }
    clr[i + 1] = mp[str];
    graph[p].push_back(i + 1);
    graph[i + 1].push_back(p);
    if (p == 0) par.push_back(i + 1);
  }
  cin >> m;
  for (int i = 0; i < m; i++) {
    int v, k;
    scanf("%d%d", &v, &k);
    qur[v].push_back(pair<int, int>(k, i));
  }
  int len = par.size();
  for (int i = 0; i < len; i++) {
    getsz(par[i], 0);
    dfs(par[i], 0, 1, 0);
  }
  for (int i = 0; i < m; i++) printf("%d\n", res[i]);
  return 0;
}
