#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
string s;
int n, m, E, tot;
int fa[N], fir[N], nex[N << 1], arr[N << 1];
int dep[N], siz[N], son[N], name[N], ans[N];
set<int> Set[N];
map<int, int> Map[N];
vector<pair<int, int> > vec[N];
map<string, int> hs;
inline void Add_Edge(int x, int y) {
  nex[++E] = fir[x];
  fir[x] = E;
  arr[E] = y;
}
void dfs(int x) {
  siz[x] = 1;
  for (int i = fir[x]; i; i = nex[i]) {
    dep[arr[i]] = dep[x] + 1;
    dfs(arr[i]);
    siz[x] += siz[arr[i]];
    if (siz[arr[i]] > siz[son[x]]) son[x] = arr[i];
  }
}
inline void Add(int x, int d) {
  if (++Map[d][x] == 1) Set[d].insert(x);
}
inline void Del(int x, int d) {
  if (--Map[d][x] == 0) Set[d].erase(x);
}
void Updata(int x, int type) {
  if (type == 1)
    Add(name[x], dep[x]);
  else
    Del(name[x], dep[x]);
  for (int i = fir[x]; i; i = nex[i]) Updata(arr[i], type);
}
void Solve(int x, int keep) {
  for (int i = fir[x]; i; i = nex[i]) {
    if (arr[i] == son[x]) continue;
    Solve(arr[i], 0);
  }
  if (son[x]) Solve(son[x], 1);
  for (int i = fir[x]; i; i = nex[i]) {
    if (arr[i] == son[x]) continue;
    Updata(arr[i], 1);
  }
  Add(name[x], dep[x]);
  for (int i = 0; i < vec[x].size(); i++) {
    ans[vec[x][i].first] = Set[vec[x][i].second].size();
  }
  if (!keep) {
    Del(name[x], dep[x]);
    for (int i = fir[x]; i; i = nex[i]) Updata(arr[i], -1);
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    cin >> s >> fa[i];
    if (!hs[s]) hs[s] = ++tot;
    name[i] = hs[s];
    Add_Edge(fa[i], i);
  }
  scanf("%d", &m);
  for (int i = 1; i <= n; i++)
    if (!fa[i]) dep[i] = 1, dfs(i);
  for (int i = 1; i <= m; i++) {
    int x, d;
    scanf("%d%d", &x, &d);
    vec[x].push_back(make_pair(i, dep[x] + d));
  }
  for (int i = 1; i <= n; i++)
    if (!fa[i]) Solve(i, 0);
  for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
  return 0;
}
