#include <bits/stdc++.h>
using namespace std;
const int maxN = 200 * 1000 + 5;
const int mod = 1000 * 1000 * 1000 + 7;
vector<int> a[maxN];
string val[maxN];
int st[maxN], fi[maxN];
int h[maxN], cnt;
int ans[maxN];
vector<pair<int, int> > r[maxN];
vector<pair<pair<int, int>, int> > que[maxN];
map<string, queue<int> > mp;
void dfs(int v, int par = -1) {
  st[v] = cnt++;
  r[h[v]].push_back(make_pair(st[v], v));
  for (auto u : a[v])
    if (u - par) h[u] = h[v] + 1, dfs(u);
  fi[v] = cnt;
}
int fen[maxN], mark[maxN];
void add(int n, int k) {
  for (; n < maxN; n += n & (-n)) fen[n] += k;
}
int get(int n) {
  int res = 0;
  for (; n > 0; n -= n & (-n)) res += fen[n];
  return res;
}
void solve(int t) {
  sort(que[t].begin(), que[t].end());
  int st = 0;
  for (int i = 0; i < r[t].size(); i++) {
    int v = r[t][i].second;
    mp[val[v]].push(i);
  }
  for (int i = 0; i < r[t].size(); i++) {
    int v = r[t][i].second;
    if (mp[val[v]].front() == i) add(i + 1, 1), mark[i] = 1;
  }
  int str = 0;
  for (int i = 0; i < r[t].size(); i++) {
    while (str < que[t].size() && que[t][str].first.first == i) {
      ans[que[t][str].second] = get(que[t][str].first.second);
      str++;
    }
    if (mark[i]) {
      mark[i] = 0;
      add(i + 1, -1);
      int v = r[t][i].second;
      mp[val[v]].pop();
      if (mp[val[v]].size()) {
        mark[mp[val[v]].front()] = 1;
        add(mp[val[v]].front() + 1, 1);
      }
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> ro;
  for (int i = 0; i < n; i++) {
    int p;
    cin >> val[i] >> p;
    p--;
    if (p == -1) {
      ro.push_back(i);
      continue;
    }
    a[p].push_back(i);
  }
  for (int i = 0; i < ro.size(); i++) dfs(ro[i]);
  int q;
  cin >> q;
  for (int i = 0; i < q; i++) {
    int v, le;
    cin >> v >> le;
    v--;
    int tmp = le + h[v];
    int lp = lower_bound(r[tmp].begin(), r[tmp].end(), make_pair(st[v], -1)) -
             r[tmp].begin();
    int rp = lower_bound(r[tmp].begin(), r[tmp].end(), make_pair(fi[v], maxN)) -
             r[tmp].begin();
    que[tmp].push_back(make_pair(make_pair(lp, rp), i));
  }
  for (int i = 0; i < n; i++) solve(i);
  for (int i = 0; i < q; i++) cout << ans[i] << endl;
  return 0;
}
