#include <bits/stdc++.h>
using namespace std;
vector<int> adj[100010];
vector<pair<int, int> > point[100010];
map<pair<int, int>, int> vis;
int n, v, k, depth[100010], pos[100010][2], tot;
char s[100010][23];
void Dfs(int k, int d) {
  pos[k][0] = ++tot;
  point[d].push_back(make_pair(tot, k));
  depth[k] = d;
  for (vector<int>::iterator p = adj[k].begin(); p != adj[k].end(); ++p) {
    Dfs(*p, d + 1);
  }
  pos[k][1] = ++tot;
}
int solve() {
  if (vis[make_pair(v, k)]) return vis[make_pair(v, k)] - 1;
  vector<pair<int, int> >::iterator l, r;
  set<string> str;
  l = lower_bound(point[depth[v] + k].begin(), point[depth[v] + k].end(),
                  make_pair(pos[v][0], 100010));
  r = lower_bound(point[depth[v] + k].begin(), point[depth[v] + k].end(),
                  make_pair(pos[v][1], 0));
  for (vector<pair<int, int> >::iterator p = l; p != r; ++p) {
    str.insert(s[(*p).second]);
  }
  return (vis[make_pair(v, k)] = str.size() + 1) - 1;
}
int main() {
  int p, m, i;
  scanf("%d", &n);
  for (i = 1; i <= n; ++i) {
    scanf("%s%d", &s[i], &p);
    adj[p].push_back(i);
  }
  Dfs(0, 0);
  scanf("%d", &m);
  while (m--) {
    scanf("%d%d", &v, &k);
    printf("%d\n", solve());
  }
  return 0;
}
