#include <bits/stdc++.h>
using namespace std;
int read() {
  int x = 0, y = 1;
  char ch = ' ';
  for (; (ch != '-' && (ch > '9' || ch < '0')); ch = getchar())
    ;
  if (ch == '-') y = -1, ch = getchar();
  for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - 48;
  return x * y;
}
const int N = 1e5 + 10;
struct node {
  int to, nex;
} e[N << 1];
int bgn[N], d[N], c[N], sz[N], son[N], ans[N];
string s[N];
map<string, int> mp[N];
vector<pair<int, int> > v[N];
int n, m, cnt, ban;
void add(int x, int y) {
  e[++cnt] = (node){y, bgn[x]};
  bgn[x] = cnt;
}
void dfs(int x, int fa) {
  sz[x] = 1;
  d[x] = d[fa] + 1;
  for (register int i = bgn[x]; i; i = e[i].nex) {
    int y = e[i].to;
    if (y == fa) continue;
    dfs(y, x);
    sz[x] += sz[y];
    if (sz[y] > sz[son[x]]) son[x] = y;
  }
}
void cal(int x, int fa, int op) {
  mp[d[x]][s[x]] += op;
  if (op < 0 && mp[d[x]][s[x]] == 0)
    --c[d[x]];
  else if (op > 0 && mp[d[x]][s[x]] == 1)
    ++c[d[x]];
  for (register int i = bgn[x]; i; i = e[i].nex) {
    int y = e[i].to;
    if (y == fa || y == ban) continue;
    cal(y, x, op);
  }
}
void solve(int x, int fa, int op) {
  for (register int i = bgn[x]; i; i = e[i].nex) {
    int y = e[i].to;
    if (y == fa || y == son[x]) continue;
    solve(y, x, 1);
  }
  if (son[x]) {
    solve(son[x], x, 0);
    ban = son[x];
  }
  cal(x, fa, 1);
  for (register int i = 0; i < v[x].size(); ++i) {
    int u = v[x][i].first, p = v[x][i].second;
    if (d[x] + u <= n + 1) ans[p] = c[d[x] + u];
  }
  ban = 0;
  if (op) cal(x, fa, -1);
}
int main() {
  int x, y, z, k;
  n = read();
  for (register int i = 1; i <= n; ++i) {
    cin >> s[i];
    x = read();
    if (x == 0) x = n + 1;
    add(x, i);
    add(i, x);
  }
  dfs(n + 1, 0);
  m = read();
  for (register int i = 1; i <= m; ++i) {
    x = read();
    y = read();
    v[x].push_back(make_pair(y, i));
  }
  solve(n + 1, 0, 0);
  for (register int i = 1; i <= m; ++i) printf("%d\n", ans[i]);
  return 0;
}
