#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using ld = long double;

vector <int> graf[200005];
int in[200005];
int out[200005];

int tjm;

vector <int> vec[500005];

void dfs(int v, int d){
    in[v] = ++tjm;
    vec[d].push_back(in[v]);
    for(auto c : graf[v]) dfs(c, d+1);
    out[v] = ++tjm;
}

int main(){
    ios_base::sync_with_stdio(false), cin.tie(0);
    cout.precision(10);
    cout << fixed;

    int n;
    cin >> n;
    for(int i=2; i<=n; i++){
        int x;
        cin >> x;
        graf[x].push_back(i);
    }
    dfs(1, 0);
    int q;
    cin >> q;
    while(q--){
        int u, d;
        cin >> u >> d;
        auto l = lower_bound(vec[d].begin(), vec[d].end(), in[u]);
        auto r = lower_bound(vec[d].begin(), vec[d].end(), out[u]);
        r--;
        if(l == vec[d].end()){
            cout << "0\n";
            continue;
        }
        cout << r-l+1 << "\n";
    }
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;

const int maxn = 200005;
vector<int> G[maxn];
vector<P> g[maxn];
struct node
{
    int u, d;
} arr[maxn];
int siz[maxn], hson[maxn], ans[maxn], d[maxn], d1[maxn];
int dfs0(int u, int f, int t)
{
    siz[u] = 1;
    d[u] = t;
    int maxx = 0;
    for (int i = 0; i < G[u].size(); i++)
    {
        int v = G[u][i];
        if (v == f)
            continue;
        siz[u] += dfs0(v, u, t + 1);
        if (siz[v] > maxx)
        {
            hson[u] = v;
            maxx = siz[v];
        }
    }
    return siz[u];
}

void jisuan(int u, int w, int ad)
{
    d1[d[u]] += ad;
    for (auto v : G[u])
    {
        if (v == w)
            continue;
        jisuan(v, w, ad);
    }
}

void dfs1(int u, int f, int keep)
{
    for (int i = 0; i < G[u].size(); i++)
    {
        int v = G[u][i];
        if (v == f || v == hson[u])
            continue;
        dfs1(v, u, 0);
    }
    if (hson[u] != 0)
        dfs1(hson[u], u, 1);
    jisuan(u, hson[u], 1); /*
    cout << u << "-------" << d[u] << endl;
    for (int i = 0; i <= 8; i++)
        cout << d1[i] << " ";
    cout << endl;*/
    for (auto p : g[u])
    {
        ans[p.second] = d1[p.first];
    }
    if (!keep)
    {
        jisuan(u, 0, -1);
    }
}

int main()
{
    ios::sync_with_stdio(false), cin.tie(nullptr);
    int n, m, i, j;
    cin >> n;
    for (i = 2; i <= n; i++)
    {
        cin >> m;
        G[m].push_back(i);
    }
    int q;
    cin >> q;
    for (int i = 0; i < q; i++)
    {
        int x, y;
        cin >> x >> y;
        g[x].emplace_back(y, i);
    }
    dfs0(1, 1, 0);
    dfs1(1, 1, 0);
    for (i = 0; i < q; i++)
        cout << ans[i] << '\n';
    return 0;
}
