#include <bits/stdc++.h>
using namespace std;
const int N = 300010;
unordered_map<string, int> m[N];
int sz[N], bigchild[N], lev[N], ans[N];
vector<int> adj[N];
vector<pair<int, int> > q[N];
string s[N];
void compute(int i, int p) {
  sz[i] = 1;
  for (auto ve : adj[i]) {
    lev[ve] = lev[i] + 1;
    compute(ve, i);
    sz[i] += sz[ve];
  }
}
void add(int i, int p) {
  m[lev[i]][s[i]]++;
  for (auto ve : adj[i])
    if (!bigchild[ve]) add(ve, i);
}
void rem(int i, int p) {
  auto it = m[lev[i]].find(s[i]);
  it->second--;
  if (!it->second) m[lev[i]].erase(s[i]);
  for (auto ve : adj[i])
    if (!bigchild[ve]) rem(ve, i);
}
void dfs(int i, int p, int keep) {
  int mx = 0, sc = -1;
  for (auto ve : adj[i])
    if (sz[ve] > mx) {
      mx = sz[ve];
      sc = ve;
    }
  for (auto ve : adj[i]) {
    if (ve - sc) dfs(ve, i, 1);
  }
  if (sc + 1) {
    dfs(sc, i, 0);
    bigchild[sc] = 1;
  }
  add(i, p);
  if (sc + 1) {
    bigchild[sc] = 0;
  }
  for (auto query : q[i]) {
    ans[query.second] = m[lev[i] + query.first].size();
  }
  if (keep) rem(i, p);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t, n, i, j, k, r, root, v;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> s[i] >> r;
    adj[r].push_back(i);
  }
  root = 0;
  cin >> r;
  for (i = 0; i < r; i++) {
    cin >> v >> k;
    q[v].push_back(make_pair(k, i));
  }
  compute(root, -1);
  dfs(root, -1, 0);
  for (i = 0; i < r; i++) cout << ans[i] << "\n";
  return 0;
}
