#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int n, m, tot, Son, col, lnk[maxn], son[maxn], nxt[maxn], maxson[maxn], c[maxn],
    siz[maxn], dep[maxn];
int tot1, lnkq[maxn], sonq[maxn], idq[maxn], nxtq[maxn], ans[maxn];
string s;
map<string, int> hsh1;
map<int, bool> hsh[maxn];
void add(int x, int y) { son[++tot] = y, nxt[tot] = lnk[x], lnk[x] = tot; }
void addq(int x, int y, int z) {
  sonq[++tot1] = y, idq[tot1] = z, nxtq[tot1] = lnkq[x], lnkq[x] = tot1;
}
void dfs1(int x) {
  siz[x] = 1;
  for (int j = lnk[x]; j; j = nxt[j]) {
    dep[son[j]] = dep[x] + 1;
    dfs1(son[j]);
    siz[x] += siz[son[j]];
    if (siz[son[j]] > siz[maxson[x]]) maxson[x] = son[j];
  }
}
void calc(int x, int op) {
  if (op == 1)
    hsh[dep[x]][c[x]] = 1;
  else
    hsh[dep[x]].clear();
  for (int j = lnk[x]; j; j = nxt[j])
    if (son[j] != Son) calc(son[j], op);
}
void dfs(int x, bool pd) {
  for (int j = lnk[x]; j; j = nxt[j])
    if (son[j] != maxson[x]) dfs(son[j], 0);
  if (maxson[x]) dfs(maxson[x], 1), Son = maxson[x];
  calc(x, 1);
  Son = 0;
  for (int j = lnkq[x]; j; j = nxtq[j]) {
    int h = dep[x] + sonq[j];
    if (h > n) continue;
    ans[idq[j]] = hsh[h].size();
  }
  if (!pd) calc(x, -1);
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    cin >> s;
    int x;
    scanf("%d", &x);
    add(x, i);
    if (hsh1[s] == 0) hsh1[s] = ++col;
    c[i] = hsh1[s];
  }
  scanf("%d", &m);
  for (int i = 1; i <= m; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    addq(x, y, i);
  }
  for (int j = lnk[0]; j; j = nxt[j]) dfs1(son[j]);
  for (int j = lnk[0]; j; j = nxt[j]) dfs(son[j], 0);
  for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
  return 0;
}
