#include <bits/stdc++.h>   using namespace std;   const int inf = 1e5 + 9, lg = 20;   int n, q, timer = 1;   vector<int> adj[inf], level[inf];   int depth[inf], in[inf], out[inf], parent[inf][lg];   void dfs(int u, int par) {     in[u] = timer++;     level[depth[u]].push_back(in[u]);     for (auto v : adj[u])       if (v != par) parent[v][0] = u, depth[v] = depth[u] + 1, dfs(v, u);     out[u] = timer++;   }   int KthParent(int u, int k) {     for (int j = lg - 1; j >= 0; j--)       if (k & (1ll << j)) u = parent[u][j];     return u;   }   int CntLevelInSubtree(int u, int h) {     return upper_bound(level[h].begin(), level[h].end(), out[u]) -            lower_bound(level[h].begin(), level[h].end(), in[u]);   }   int main() {     cin >> n;     for (int i = 1; i <= n; i++) {       int tmp;       cin >> tmp;       if (tmp) adj[tmp].push_back(i), adj[i].push_back(tmp);     }     for (int i = 1; i <= n; i++)       if (!in[i]) dfs(i, 0);     for (int j = 1; j < lg; j++)       for (int i = 1; i <= n; i++) parent[i][j] = parent[parent[i][j - 1]][j - 1];     cin >> q;     while (q--) {       int v, p;       cin >> v >> p;       if (depth[v] < p) {         cout << 0 <<    ;         continue;       }       int u = KthParent(v, p);       cout << CntLevelInSubtree(u, depth[v]) - 1 <<    ;     }   }   