#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;

template<class T>
bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; }
template<class T>
bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }

using ll = long long;
using P = pair<int, int>;
using vvi = vector<vector<int>>;
using vi = vector<int>;

const ll MOD = 1e9 + 7;
const int INF = 1001001001;
const double PI = 3.14159265358979323846;

int timer = 0;

void dfs(int now, int d, vvi &to, vvi &din, vector<P> &inout) {
    inout[now].first = timer;
    din[d].push_back(timer);
    timer++;
    for (auto ni : to[now]) {
        dfs(ni, d+1, to, din, inout);
    }
    inout[now].second = timer;
}

void solve() {
    int n;
    cin >> n;
    vvi to(n), din(n);
    vector<P> inout(n);
    rep(i, n-1) {
        int p;
        cin >> p;
        p--;
        to[p].push_back(i+1);
    }
   
    dfs(0, 0, to, din, inout);

    int q;
    cin >> q;
    rep(x, q) {
        int u, d;
        cin >> u >> d;
        u--;
        auto [tin, tout] = inout[u];
        auto now = din[d];
        auto it_out = lower_bound(now.begin(), now.end(), tout);
        auto it_in = lower_bound(now.begin(), now.end(), tin);
        int num_out = distance(now.begin(), it_out);
        int num_in = distance(now.begin(), it_in);
        int ans = num_out - num_in;
        cout << ans << endl;
    }
}

int main() {

    solve();

    return 0;
}

#include <algorithm>
#include <iostream>
#include <vector>

void dfs(const std::vector<int> &C, const std::vector<std::vector<unsigned long>> &edge, unsigned long idx, std::vector<unsigned long> &ans, std::vector<bool> &used, std::vector<bool> &checked)
{
    if (checked[idx])
    {
        return;
    }
    else
    {
        checked[idx] = true;
    }
    if (!used[C[idx]])
    {
        ans.push_back(idx);
        used[C[idx]] = true;
        for (const auto &e : edge[idx])
        {
            dfs(C, edge, e, ans, used, checked);
        }
        used[C[idx]] = false;
    }
    else
    {
        for (const auto &e : edge[idx])
        {
            dfs(C, edge, e, ans, used, checked);
        }
    }
}

int main()
{
    unsigned long N;
    std::cin >> N;
    std::vector<int> C(N);
    for (unsigned long i = 0ul; i < N; ++i)
    {
        std::cin >> C[i];
    }
    std::vector<std::vector<unsigned long>> edge(N, std::vector<unsigned long>());
    for (unsigned long i = 0ul; i < N - 1; ++i)
    {
        unsigned long A, B;
        std::cin >> A >> B;
        --A;
        --B;
        edge.at(A).push_back(B);
        edge.at(B).push_back(A);
    }
    std::vector<unsigned long> ans;
    std::vector<bool> color_used(200000, false);
    std::vector<bool> checked(N, false);
    dfs(C, edge, 0, ans, color_used, checked);
    std::sort(ans.begin(), ans.end());
    for (const auto &c : ans)
    {
        std::cout << c + 1 << std::endl;
    }
    return 0;
}
