#include <bits/stdc++.h>
using namespace std;
int n, q;
vector<int> root;
vector<pair<int, int> > query[100005];
vector<int> adj[100005];
unordered_map<string, int> mapa;
int v[100005], ans[100005], t;
int pesado[100005], deep[100005], ini[100005], fim[100005], tempo[100005],
    tam[100005];
void dfs(int x) {
  tam[x] = 1;
  tempo[t] = x;
  ini[x] = t++;
  pesado[x] = -1;
  for (int i = 0, y; i < ((int)(adj[x]).size()); i++) {
    y = adj[x][i];
    deep[y] = deep[x] + 1;
    dfs(y);
    tam[x] += tam[y];
    if (pesado[x] == -1 || tam[y] > tam[pesado[x]]) pesado[x] = y;
  }
  fim[x] = t;
}
unordered_set<int> conju[100005 * 2];
unordered_set<int>::iterator it;
void solve(int x, int pai) {
  for (int i = 0, y; i < ((int)(adj[x]).size()); i++) {
    y = adj[x][i];
    if (y == pesado[x]) continue;
    solve(y, x);
  }
  if (pesado[x] != -1) solve(pesado[x], x);
  for (int i = 0, y; i < ((int)(adj[x]).size()); i++) {
    y = adj[x][i];
    if (y == pesado[x]) continue;
    for (int j = ini[y]; j < fim[y]; j++) {
      conju[deep[tempo[j]]].insert(v[tempo[j]]);
    }
  }
  for (int i = 0, h, idx; i < ((int)(query[x]).size()); i++) {
    h = query[x][i].first;
    idx = query[x][i].second;
    ans[idx] = ((int)(conju[deep[x] + h]).size());
  }
  conju[deep[x]].insert(v[x]);
  if (x != pesado[pai]) {
    for (int i = ini[x]; i < fim[x]; i++) {
      it = conju[deep[tempo[i]]].find(v[tempo[i]]);
      if (it != conju[deep[tempo[i]]].end()) conju[deep[tempo[i]]].erase(it);
    }
  }
}
int main() {
  scanf("%d", &n);
  char s[30];
  for (int i = 0, cnt = 0, p; i < n; i++) {
    scanf("%29s", s);
    scanf("%d", &p);
    p--;
    if (p == -1)
      root.push_back(i);
    else
      adj[p].push_back(i);
    if (mapa.find(s) == mapa.end()) mapa[s] = cnt++;
    v[i] = mapa[s];
  }
  scanf("%d", &q);
  for (int i = 0, x, k; i < q; i++) {
    scanf("%d %d", &x, &k);
    x--;
    query[x].push_back(make_pair(k, i));
  }
  pesado[100005 + 1] = -1;
  for (int i = 0; i < ((int)(root).size()); i++) {
    dfs(root[i]);
    solve(root[i], 100005 + 1);
  }
  for (int i = 0; i < q; i++) printf("%d\n", ans[i]);
}
