#include <bits/stdc++.h>
using namespace std;
vector<int> mat[500010];
vector<pair<int, int> > quer[500010];
int lf[500010], rg[500010], lev[500010], bigC[500010], sz[500010], dfa[500010],
    ti;
void dfs(int p, int pa) {
  lf[p] = ++ti;
  sz[p] = 1;
  dfa[ti] = p;
  int mx = -1;
  bigC[p] = -1;
  for (auto x : mat[p]) {
    if (x == pa) continue;
    lev[x] = lev[p] + 1;
    dfs(x, p);
    sz[p] += sz[x];
    if (sz[x] > mx) mx = sz[x], bigC[p] = x;
  }
  rg[p] = ti;
}
int prin[500010], col[500010];
set<int> occ[500010];
void update(int p, int v) {
  int l = lev[p];
  if (v == 1)
    occ[l].insert(col[p]);
  else
    occ[l].erase(col[p]);
  return;
}
int dsu(int p, int pa, int keep) {
  for (auto x : mat[p])
    if (x != pa && x != bigC[p]) dsu(x, p, 0);
  if (bigC[p] != -1) dsu(bigC[p], p, 1);
  update(p, 1);
  for (auto x : mat[p]) {
    if (x == pa || x == bigC[p]) continue;
    for (int i = lf[x]; i <= rg[x]; i++) update(dfa[i], 1);
  }
  for (auto x : quer[p]) {
    int l = lev[p] + x.first;
    if (l < 500010) prin[x.second] = occ[l].size();
  }
  if (!keep)
    for (int i = lf[p]; i <= rg[p]; i++) update(dfa[i], -1);
}
unsigned int getHash(string str) {
  int n = str.size();
  unsigned int ret = 0, ba = 31, c;
  for (int i = 0; i <= n - 1; i++) {
    c = str[i] - 'a';
    c++;
    ret += (ba * c);
    ba *= 31;
  }
  return ret;
}
map<unsigned int, int> mopa;
string str;
int getId(string str) {
  unsigned int v = getHash(str);
  if (mopa[v] == 0) mopa[v] = mopa.size();
  return mopa[v];
}
vector<int> Root;
int main() {
  ios::sync_with_stdio(false);
  int n, u, v, q, root;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    u = i;
    cin >> str >> v;
    if (v) mat[u].push_back(v);
    if (v) mat[v].push_back(u);
    col[i] = getId(str);
    if (v == 0) Root.push_back(u);
  }
  cin >> q;
  for (int i = 0; i <= q - 1; i++) {
    cin >> u >> v;
    quer[u].push_back({v, i});
  }
  for (auto root : Root) {
    dfs(root, root);
    dsu(root, root, 0);
  }
  for (int i = 0; i <= q - 1; i++) cout << prin[i] << endl;
  return 0;
}
