#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
vector<int> grafo[maxn];
int n, m, sz[maxn], level[maxn], big[maxn], ans[maxn];
string cor[maxn];
map<string, int> freq[maxn];
vector<pair<int, int> > q[maxn];
void dfs(int u) {
  sz[u] = 1;
  for (auto v : grafo[u]) {
    level[v] = level[u] + 1;
    dfs(v);
    sz[u] += sz[v];
  }
}
void add(int u, int x) {
  freq[level[u]][cor[u]] += x;
  if (!freq[level[u]][cor[u]]) freq[level[u]].erase(cor[u]);
  for (auto v : grafo[u])
    if (!big[v]) add(v, x);
}
void sack(int u, bool keep) {
  int idmax = 0;
  for (auto v : grafo[u])
    if (sz[idmax] < sz[v]) idmax = v;
  for (auto v : grafo[u])
    if (v != idmax) sack(v, 0);
  if (idmax) sack(idmax, 1), big[idmax] = 1;
  add(u, 1);
  for (auto x : q[u])
    if (level[u] + x.second < maxn)
      ans[x.first] = (int)freq[level[u] + x.second].size();
  big[idmax] = 0;
  if (!keep) add(u, -1);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int p;
    cin >> cor[i] >> p;
    grafo[p].push_back(i);
  }
  cin >> m;
  for (int i = 1; i <= m; i++) {
    int v, k;
    cin >> v >> k;
    q[v].push_back({i, k});
  }
  for (int i = 1; i <= n; i++) {
    if (!sz[i]) {
      dfs(i);
      sack(i, 0);
    }
  }
  for (int i = 1; i <= m; i++) cout << ans[i] << "\n";
  return 0;
}
