#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m, t, par, num, Size, Start[N], End[N], Depth[N], bit[N], pr[N];
map<int, int> last, save;
map<string, int> id;
set<int> RowSet;
vector<int> adj[N];
vector<pair<int, int> > Row[N];
struct node {
  int id, l, r;
  bool operator<(const node& cmp) const { return r < cmp.r; }
};
vector<node> req[N];
void Build_Graph() {
  string s;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> s >> par;
    if (id[s] == 0) id[s] = ++t;
    save[i] = id[s], adj[par].push_back(i);
  }
}
void DFS_Order(int node, int depth) {
  Start[node] = ++num, Depth[node] = depth;
  Row[Depth[node]].push_back(make_pair(Start[node], node));
  for (int i = 0; i < adj[node].size(); i++) DFS_Order(adj[node][i], depth + 1);
  End[node] = ++num;
}
void Build_Queries() {
  node nd;
  int row, a, b;
  cin >> m;
  for (int i = 0; i < m; i++) {
    cin >> a >> b;
    row = Depth[a] + b, nd.id = i;
    nd.l =
        lower_bound(Row[row].begin(), Row[row].end(), make_pair(Start[a], 0)) -
        Row[row].begin();
    nd.r = lower_bound(Row[row].begin(), Row[row].end(), make_pair(End[a], 0)) -
           Row[row].begin();
    if (nd.l == nd.r)
      pr[nd.id] = 0;
    else
      req[row].push_back(nd), RowSet.insert(row);
  }
}
void Add(int ind, int val) {
  while (ind <= Size) {
    bit[ind] += val;
    ind += ind & (-ind);
  }
}
int Query(int ind) {
  int ret = 0;
  while (ind > 0) {
    ret += bit[ind];
    ind -= ind & (-ind);
  }
  return ret;
}
void Solve() {
  for (set<int>::iterator it = RowSet.begin(); it != RowSet.end(); it++) {
    int i = (*it), x = 1;
    Size = Row[i].size();
    last.clear();
    sort(req[i].begin(), req[i].end());
    memset(bit, 0, sizeof bit);
    for (int j = 0; j < req[i].size(); j++) {
      int Id = req[i][j].id, L = req[i][j].l + 1, R = req[i][j].r;
      for (; x <= R; x++) {
        int val = save[Row[i][x - 1].second];
        if (last[val] != 0) Add(last[val], -1);
        Add(x, 1), last[val] = x;
      }
      pr[Id] = Query(R) - Query(L - 1);
    }
  }
}
int main() {
  Build_Graph();
  DFS_Order(0, 0);
  Build_Queries();
  Solve();
  for (int i = 0; i < m; i++) cout << pr[i] << "\n";
  return 0;
}
