#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e5 + 100;
vector<int> g[MAXN], Q[MAXN];
int sz[MAXN], c[MAXN], big[MAXN], ans[MAXN];
int v[MAXN], ht[MAXN], depth[MAXN];
map<string, int> cnt[MAXN];
map<int, int> res[MAXN];
string a[MAXN];
map<string, int>::iterator it;
void dfs0(int x, int h) {
  sz[x] = 1;
  depth[x] = h;
  for (int i = 0; i < g[x].size(); ++i) {
    int u = g[x][i];
    dfs0(u, h + 1);
    sz[x] += sz[u];
  }
}
void add(int x) {
  cnt[depth[x]][a[x]]++;
  for (int i = 0; i < g[x].size(); ++i) {
    int u = g[x][i];
    if (!big[u]) add(u);
  }
}
void rem(int v) {
  it = cnt[depth[v]].find(a[v]);
  it->second--;
  if (!it->second) cnt[depth[v]].erase(it);
  for (int i = 0; i < g[v].size(); ++i) {
    int u = g[v][i];
    if (!big[u]) rem(u);
  }
}
void dfs(int x, int keep) {
  int mx = 0, bigc = 0;
  for (int i = 0; i < g[x].size(); ++i) {
    int u = g[x][i];
    if (mx < sz[u]) mx = sz[u], bigc = u;
  }
  for (int i = 0; i < g[x].size(); ++i) {
    int u = g[x][i];
    if (u != bigc) dfs(u, 1);
  }
  if (bigc) dfs(bigc, 0), big[bigc] = 1;
  add(x);
  for (int i = 0; i < Q[x].size(); ++i) {
    int h = Q[x][i];
    res[x][h + depth[x]] = cnt[h + depth[x]].size();
  }
  if (bigc) big[bigc] = 0;
  if (keep) rem(x);
}
int main() {
  ios_base::sync_with_stdio(0);
  ;
  int n, q;
  cin >> n;
  int x, y;
  a[0] = "hell";
  for (int i = 1; i < n + 1; ++i) {
    cin >> a[i] >> x;
    g[x].push_back(i);
  }
  dfs0(0, 0);
  cin >> q;
  for (int i = 0; i < q; ++i) {
    cin >> v[i] >> ht[i];
    Q[v[i]].push_back(ht[i]);
  }
  dfs(0, 0);
  for (int i = 0; i < q; ++i) {
    cout << res[v[i]][ht[i] + depth[v[i]]] << endl;
  }
}
