#include <bits/stdc++.h>
using namespace std;
map<string, int> No;
set<int> si[100005];
string str;
int col[100005], dep[100005], hson[100005], size[100005];
vector<int> tre[100005];
void init(int u) {
  size[u] = 1;
  for (int i = 0; i < tre[u].size(); i++) {
    int v = tre[u][i];
    dep[v] = dep[u] + 1;
    init(v);
    if (size[v] > size[hson[u]]) hson[u] = v;
    size[u] += size[v];
  }
}
int HS;
void add(int u, bool flag) {
  if (flag)
    si[dep[u]].insert(col[u]);
  else
    si[dep[u]].erase(col[u]);
  for (int i = 0; i < tre[u].size(); i++) {
    int v = tre[u][i];
    if (v == HS) continue;
    add(v, flag);
  }
}
struct Ques {
  int id, k;
};
vector<Ques> vq[100005];
int ans[100005];
bool vis[100005];
void dfs(int u, bool kep) {
  vis[u] = true;
  for (int i = 0; i < tre[u].size(); i++) {
    int v = tre[u][i];
    if (v != hson[u]) dfs(v, false);
  }
  if (hson[u]) {
    dfs(hson[u], true);
    HS = hson[u];
  }
  add(u, true);
  HS = 0;
  for (int i = 0; i < vq[u].size(); i++) {
    Ques q = vq[u][i];
    ans[q.id] = si[q.k].size();
  }
  if (!kep) add(u, false);
}
bool isson[100005];
int main() {
  int n, cnt = 0, rot;
  ios::sync_with_stdio(false);
  cin >> n;
  for (int i = 1, f; i <= n; i++) {
    cin >> str >> f;
    if (No[str] == 0) No[str] = ++cnt;
    col[i] = No[str];
    if (f) {
      tre[f].push_back(i);
      isson[i] = true;
    }
  }
  for (int i = 1; i <= n; i++)
    if (!isson[i]) {
      dep[i] = 1;
      init(i);
    }
  int m;
  cin >> m;
  for (int i = 1, v, d; i <= m; i++) {
    cin >> v >> d;
    if (d + dep[v] > n) continue;
    vq[v].push_back((Ques){i, d + dep[v]});
  }
  for (int i = 1; i <= n; i++)
    if (!vis[i]) dfs(i, false);
  for (int i = 1; i <= m; i++) cout << ans[i] << endl;
  return 0;
}
