#include <bits/stdc++.h>
using namespace std;
struct query {
  int id, dep;
};
const int MAX = 100005;
vector<int> g[MAX];
int depth[MAX];
int sz[MAX];
bool big[MAX];
string name[MAX];
map<string, int> mp[2 * MAX];
vector<query> qry[MAX];
int ans[MAX];
void pre(int u, int dep) {
  depth[u] = dep;
  sz[u] = 1;
  for (auto v : g[u]) {
    pre(v, dep + 1);
    sz[u] += sz[v];
  }
}
void upd(int u, int x) {
  mp[depth[u]][name[u]] += x;
  if (mp[depth[u]][name[u]] == 0) mp[depth[u]].erase(name[u]);
  for (auto v : g[u])
    if (!big[v]) upd(v, x);
}
void dfs(int u, bool keep) {
  int mx = -1, id = -1;
  for (auto v : g[u])
    if (sz[v] > mx) mx = sz[v], id = v;
  for (auto v : g[u])
    if (v != id) dfs(v, false);
  if (id != -1) dfs(id, true), big[id] = true;
  upd(u, 1);
  for (auto x : qry[u]) ans[x.id] = mp[x.dep].size();
  if (id != -1) big[id] = false;
  if (!keep) upd(u, -1);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, q;
  cin >> n;
  for (int v = 1, u; v <= n; v++) {
    cin >> name[v] >> u;
    g[u].push_back(v);
  }
  pre(0, 0);
  cin >> q;
  for (int i = 0, u, k; i < q; i++) {
    cin >> u >> k;
    qry[u].push_back({i, depth[u] + k});
  }
  dfs(0, false);
  for (int i = 0; i < q; i++) {
    cout << ans[i] << '\n';
  }
}
