#include <bits/stdc++.h>
using namespace std;
int N;
int sz[100001], ans[100001], L[100001];
vector<int> zero;
vector<int> g[100001];
vector<pair<int, int>> query[100001];
vector<int> *vec[100001];
string name[100001];
map<int, set<string>> cnt;
void subtree_size(int u, int p, int l) {
  sz[u] = 1;
  L[u] = l;
  for (int v : g[u]) {
    if (v != p) {
      subtree_size(v, u, l + 1);
      sz[u] += sz[v];
    }
  }
}
void dfs(int u, int p, bool keep) {
  int mx = -1, big_child = -1;
  for (auto &v : g[u]) {
    if (v != p && sz[v] > mx) {
      mx = sz[v], big_child = v;
    }
  }
  for (auto &v : g[u]) {
    if (v != p && v != big_child) {
      dfs(v, u, 0);
    }
  }
  if (big_child != -1) {
    dfs(big_child, u, 1);
    vec[u] = vec[big_child];
  } else {
    vec[u] = new vector<int>();
  }
  vec[u]->push_back(u);
  cnt[L[u]].insert(name[u]);
  for (auto &v : g[u]) {
    if (v != p && v != big_child) {
      for (auto &it : *vec[v]) {
        vec[u]->push_back(it);
        cnt[L[it]].insert(name[it]);
      }
    }
  }
  for (pair<int, int> q : query[u]) {
    ans[q.second] = cnt[L[u] + q.first].size();
  }
  if (keep == 0) {
    for (auto &it : *vec[u]) {
      cnt[L[it]].erase(name[it]);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n, m, u, p, i;
  cin >> n;
  N = n;
  for (i = 1; i <= n; i++) {
    cin >> name[i];
    cin >> p;
    if (p == 0)
      zero.push_back(i);
    else {
      g[p].push_back(i);
      g[i].push_back(p);
    }
  }
  for (int u : zero) subtree_size(u, -1, 0);
  cin >> m;
  for (i = 1; i <= m; i++) {
    cin >> u >> p;
    query[u].push_back({p, i});
  }
  for (int u : zero) dfs(u, -1, 0);
  for (i = 1; i <= m; i++) {
    cout << ans[i] << "\n";
  }
  return 0;
}
