#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
unordered_map<string, int> mp[N];
string str[N];
int depth[N], sz[N], heav[N], co[N], ans[N], dm;
vector<int> adj[N];
vector<bool> big(N);
vector<pair<int, int> > q[N];
void getsz(int s) {
  sz[s] = 1;
  int ma = -1;
  for (auto it : adj[s]) {
    depth[it] = depth[s] + 1;
    dm = max(dm, depth[it]);
    getsz(it);
    sz[s] += sz[it];
    if (sz[it] > ma) {
      ma = sz[it];
      heav[s] = it;
    }
  }
}
void rem(int s) {
  int k = --mp[depth[s]][str[s]];
  if (k == 0) co[depth[s]]--;
  for (auto it : adj[s]) {
    if (!big[it]) rem(it);
  }
}
void add(int s) {
  int k;
  k = ++mp[depth[s]][str[s]];
  if (k == 1) co[depth[s]]++;
  for (auto it : adj[s]) {
    if (!big[it]) {
      add(it);
    }
  }
}
void dfs(int s, bool isbig) {
  for (auto it : adj[s]) {
    if (it != heav[s]) dfs(it, 0);
  }
  if (heav[s] != -1) {
    dfs(heav[s], 1);
    big[heav[s]] = 1;
  }
  add(s);
  if (heav[s] != -1) big[heav[s]] = 0;
  for (int i = 0; i < q[s].size(); i++) {
    if (depth[s] + q[s][i].first <= dm)
      ans[q[s][i].second] = co[depth[s] + q[s][i].first];
    else
      ans[q[s][i].second] = 0;
  }
  if (!isbig) rem(s);
}
int main() {
  int n, r, i, m;
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  memset(heav, -1, sizeof(heav));
  for (i = 1; i <= n; i++) {
    cin >> str[i];
    cin >> r;
    adj[r].push_back(i);
  }
  cin >> m;
  for (i = 0; i < m; i++) {
    int v, k;
    cin >> v >> k;
    q[v].push_back({k, i});
  }
  getsz(0);
  dfs(0, 1);
  for (i = 0; i < m; i++) cout << ans[i] << "\n";
}
