#include <bits/stdc++.h>
using namespace std;
const int INF = std::numeric_limits<int>::max();
const char* IN_FILE = ".in";
const char* OUT_FILE = ".out";
int n;
const int NMAX = 100005;
vector<int> g[NMAX];
int nameId[NMAX];
deque<set<int>*>* d[NMAX];
vector<pair<int, int> > q[NMAX];
int ans[NMAX];
void dfs(int v, int p) {
  bool isLeaf = true;
  int maxHeightId = -1;
  for (int i = 0; i < int((g[v]).size()); ++i) {
    int u = g[v][i];
    if (u == p) continue;
    isLeaf = false;
    dfs(u, v);
    if (maxHeightId == -1 || (d[maxHeightId]->size() < d[u]->size())) {
      maxHeightId = u;
    }
  }
  d[v] = new deque<set<int>*>();
  if (isLeaf) {
    d[v]->push_back(new set<int>());
    (*d[v])[0]->insert(nameId[v]);
  } else {
    assert(maxHeightId != -1);
    d[v] = d[maxHeightId];
    deque<set<int>*>& currentD = *d[v];
    for (int i = 0; i < int((g[v]).size()); ++i) {
      int u = g[v][i];
      if (u == p) continue;
      if (u == maxHeightId) continue;
      for (int j = 0; j < int((*d[u]).size()); ++j) {
        if (j >= currentD.size()) {
          assert(false);
        } else {
          if (currentD[j]->size() < (*d[u])[j]->size()) {
            swap(currentD[j], (*d[u])[j]);
          }
          currentD[j]->insert((*d[u])[j]->begin(), (*d[u])[j]->end());
          delete (*d[u])[j];
        }
      }
      d[u]->clear();
    }
    currentD.push_front(new set<int>());
    currentD[0]->insert(nameId[v]);
  }
  for (int it = 0; it < int((q[v]).size()); ++it) {
    pair<int, int> qr = q[v][it];
    if (qr.first < d[v]->size()) {
      ans[qr.second] = (*d[v])[qr.first]->size();
    }
  }
}
void solve() {
  map<string, int> name2Id;
  cin >> n;
  vector<int> roots;
  for (int i = 0; i < int(n); ++i) {
    string name;
    cin >> name;
    if (name2Id.count(name) > 0) {
      nameId[i] = name2Id[name];
    } else {
      nameId[i] = name2Id.size();
      name2Id.insert(make_pair(name, name2Id.size()));
    }
    int p;
    cin >> p;
    --p;
    if (p >= 0) {
      g[p].push_back(i);
    } else
      roots.push_back(i);
  }
  int nq;
  cin >> nq;
  for (int it = 0; it < int(nq); ++it) {
    int v, k;
    cin >> v >> k;
    --v;
    q[v].push_back(make_pair(k, it));
  }
  for (int root : roots) {
    dfs(root, -1);
    for (int i = 0; i < int((*d[root]).size()); ++i) {
      delete (*d[root])[i];
    }
    d[root]->clear();
  }
  for (int i = 0; i < int(nq); ++i) {
    cout << ans[i] << endl;
  }
}
void init() {
  freopen(IN_FILE, "rt", stdin);
  freopen(OUT_FILE, "wt", stdout);
}
int main() {
  ios_base::sync_with_stdio(false);
  solve();
  return 0;
}
