#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
const int MAXN = 100005;
int n, m;
int vis[MAXN], p[MAXN], ans[MAXN];
string str[MAXN];
vector<int> adj[MAXN];
vector<pair<int, int>> queries[MAXN];
map<int, set<int>> st[MAXN];
map<string, int> mp;
int cnt[MAXN];
void merge(int a, int b) {
  if (st[a].size() < st[b].size()) st[a].swap(st[b]);
  for (auto it : st[b]) {
    if (st[a][it.first].size() < it.second.size()) {
      swap(st[a][it.first], it.second);
    }
    for (auto t : it.second) {
      st[a][it.first].insert(t);
    }
  }
}
void dfs(int s, int p, int h) {
  st[s][h].insert(mp[str[s]]);
  for (auto t : adj[s]) {
    if (t != p) {
      dfs(t, s, h + 1);
      merge(s, t);
    }
  }
  for (auto t : queries[s]) {
    ans[t.second] = st[s][h + t.first].size();
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int idx = 0;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> str[i] >> p[i];
    if (mp.find(str[i]) == mp.end()) {
      mp[str[i]] = idx++;
    }
    adj[p[i]].push_back(i);
  }
  cin >> m;
  for (int i = 1; i <= m; i++) {
    int x, y;
    cin >> x >> y;
    queries[x].push_back({y, i});
  }
  for (int i = 1; i <= n; i++) {
    if (p[i] == 0) {
      dfs(i, 0, 0);
    }
  }
  for (int i = 1; i <= m; i++) {
    cout << ans[i] << endl;
  }
}
