#include <bits/stdc++.h>
using namespace ::std;
char name[100001][30];
int n, m, mark[100001][2], depth[100001], step;
vector<int> graph[100001], level[100001];
map<pair<int, int>, int> cache;
void dfs(int u, int d) {
  mark[u][0] = step++;
  depth[u] = d;
  level[d].push_back(u);
  for (int i = 0, sz = graph[u].size(); i < sz; i++) dfs(graph[u][i], d + 1);
  mark[u][1] = step++;
}
inline int bs(vector<int> &v, int c) {
  int i = 0, j = v.size();
  if (j == 0) return 0;
  while (i + 1 < j) {
    int m = (i + j) / 2;
    if (mark[v[m]][0] <= c)
      i = m;
    else
      j = m;
  }
  if (mark[v[i]][0] > c) return i;
  return j;
}
inline int ksons(int v, int k) {
  if (depth[v] + k > n) return 0;
  if (cache.count(make_pair(v, k))) return cache[make_pair(v, k)];
  set<string> s;
  vector<int> &ve = level[depth[v] + k];
  int tot = 0;
  for (int x = bs(ve, mark[v][0]), sz = ve.size();
       x < sz && mark[ve[x]][1] < mark[v][1]; x++) {
    s.insert(name[ve[x]]);
  }
  return cache[make_pair(v, k)] = s.size();
}
int main() {
  int a, v, k;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%s %d", &name[i][0], &a);
    graph[a].push_back(i);
  }
  dfs(0, 0);
  scanf("%d", &m);
  while (m--) {
    scanf("%d %d", &v, &k);
    printf("%d\n", ksons(v, k));
  }
  return 0;
}
