#include <bits/stdc++.h>
using namespace std;
const long long maxn = 2e5 + 10;
int head[maxn << 1], to[maxn << 1], nex[maxn << 1], e;
int fa[maxn], dep[maxn], son[maxn], siz[maxn], vis[maxn];
string a[maxn];
int sum[maxn];
vector<pair<int, int> > q[maxn];
int ans[maxn];
map<string, int> mp[maxn];
void add(int x, int y) {
  to[++e] = y;
  nex[e] = head[x];
  head[x] = e;
}
void dfs1(int x, int f, int deep) {
  siz[x] = 1;
  dep[x] = deep;
  int maxson = -1;
  for (int i = head[x]; i; i = nex[i]) {
    int y = to[i];
    if (y == f) continue;
    dfs1(y, x, deep + 1);
    siz[x] += siz[y];
    if (maxson < siz[y]) {
      maxson = siz[y];
      son[x] = y;
    }
  }
}
void upd(string a, int dep, int val) {
  if (val == 1) {
    ++mp[dep][a];
    if (mp[dep][a] == 1) ++sum[dep];
  } else {
    --mp[dep][a];
    if (mp[dep][a] == 0) --sum[dep];
  }
}
void counts(int x, int val) {
  upd(a[x], dep[x], val);
  for (int i = head[x]; i; i = nex[i]) {
    int y = to[i];
    if (y == fa[x] || vis[y]) continue;
    counts(y, val);
  }
}
void dsu(int x, int f, int hson) {
  for (int i = head[x]; i; i = nex[i]) {
    int y = to[i];
    if (y == f || y == son[x]) continue;
    dsu(y, x, 0);
  }
  if (son[x]) {
    dsu(son[x], x, 1);
    vis[son[x]] = 1;
  }
  counts(x, 1);
  for (int i = 0; i < q[x].size(); i++) {
    int y = q[x][i].second;
    ans[q[x][i].first] = sum[y];
  }
  if (son[x]) vis[son[x]] = 0;
  if (!hson) counts(x, -1);
}
int main() {
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i] >> fa[i];
    add(i, fa[i]);
    add(fa[i], i);
  }
  for (int i = 1; i <= n; i++) {
    if (!fa[i]) dfs1(i, 0, 1);
  }
  int m, x, y;
  cin >> m;
  for (int i = 1; i <= m; i++) {
    cin >> x >> y;
    q[x].push_back(make_pair(i, dep[x] + y));
  }
  for (int i = 1; i <= n; i++) {
    if (!fa[i]) dsu(i, 0, 0);
  }
  for (int i = 1; i <= m; i++) {
    printf("%d\n", ans[i]);
  }
}
