#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
struct node {
  int dep, id, nxt;
} q[N];
int n, cnt, col[N], dep[N], m, ans[N], head[N], tot, sz[N], son[N], mx;
bool vis[N];
string tmp;
map<string, int> mp;
map<int, int> st[N];
map<int, int>::iterator it;
vector<int> e[N];
inline void add(int x, int k, int i) {
  q[++tot] = (node){k, i, head[x]};
  head[x] = tot;
}
inline void dfs(int x) {
  sz[x] = 1;
  mx = max(mx, dep[x]);
  for (int i = 0; i < (int)e[x].size(); i++) {
    int v = e[x][i];
    dep[v] = dep[x] + 1;
    dfs(v);
    sz[x] += sz[v];
    son[x] = sz[son[x]] > sz[v] ? son[x] : v;
  }
}
inline void update(int x, int v) {
  st[dep[x]][col[x]] += v;
  if (st[dep[x]][col[x]] == 0) {
    it = st[dep[x]].find(col[x]);
    st[dep[x]].erase(it);
  }
  for (int i = 0; i < (int)e[x].size(); i++)
    if (!vis[e[x][i]]) update(e[x][i], v);
}
inline void Dfs(int x, int keep) {
  if (x == 0) return;
  for (int i = 0; i < (int)e[x].size(); i++) {
    int v = e[x][i];
    if (v == son[x]) continue;
    Dfs(v, 0);
  }
  Dfs(son[x], 1);
  vis[son[x]] = 1;
  update(x, 1);
  vis[son[x]] = 0;
  for (int i = head[x]; i; i = q[i].nxt) {
    int now = dep[x] + q[i].dep;
    if (now <= mx) ans[q[i].id] += st[now].size();
  }
  if (!keep) update(x, -1);
}
int main() {
  scanf("%d", &n);
  for (int i = 1, x; i <= n; i++) {
    cin >> tmp;
    scanf("%d\n", &x);
    e[x].push_back(i);
    if (!mp.count(tmp)) mp[tmp] = ++cnt;
    col[i] = mp[tmp];
  }
  scanf("%d", &m);
  for (int i = 1, x, k; i <= m; i++) {
    scanf("%d%d\n", &x, &k);
    add(x, k, i);
  }
  dfs(0);
  for (int i = 0; i < (int)e[0].size(); i++) {
    int v = e[0][i];
    Dfs(v, 0);
  }
  for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
  return 0;
}
