#include <iostream>
#include <vector>
#include <algorithm>
std::vector<std::vector<int>> children, list;
std::vector<int> in, out, depth;
int timer;
void dfs(const int u) {
    in[u] = timer++;
    list[depth[u]].push_back(in[u]);
    for (const int v : children[u]) {
        depth[v] = depth[u] + 1;
        dfs(v);
    }
    out[u] = timer++;
}
int main() {
    int N;
    std::cin >> N;
    children = list = std::vector<std::vector<int>>(N);
    in = out = depth = std::vector<int>(N);
    for (int i = 1; i < N; ++i) {
        int p;
        std::cin >> p;
        children[p - 1].push_back(i);
    }
    dfs(0);
    int Q;
    std::cin >> Q;
    while (Q--) {
        int u, d;
        std::cin >> u >> d;
        u -= 1;
        const auto& v = list[d];
        std::cout << std::lower_bound(v.cbegin(), v.cend(), out[u]) - std::lower_bound(v.cbegin(), v.cend(), in[u]) << '\n';
    }
    return 0;
}
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
#define all(v) v.begin(), v.end()
#define pb push_back    
#define sz(x) (int)(x).size()
const int N = 3e5 + 5;
void solve() {

    int n, m;
    scanf("%d%d", &n, &m);
    vector<vi> g(n);
    vi cur, col(n, 0), vis(n, 0);

    for(int i = 0; i < m; ++i) {
        int u, v;
        scanf("%d%d", &u, &v);
        g[--u].pb(--v);
        g[v].pb(u);
    }
 
    auto check = [&](int u, int c) {
        for(auto v : g[u]){
            if(col[v] == c)
                return 0;
        }
        return 1;
    };

    function<void(int)> make = [&](int u) {
        cur.pb(u);
        vis[u] = 1;
        for(int v : g[u])
            if(!vis[v])
                make(v);
    };

    function<int(int, int)> dfs = [&](int u, int c) -> int {
        if(u == sz(cur) - 1) {
            return 1;
        }
        int ret = 0;
        for(int i = 1; i <= 3; ++i) {
            if(check(cur[u + 1], i)) {
                col[cur[u + 1]] = i;
                ret += dfs(u + 1, i);
                col[cur[u + 1]] = 0;
            }
        }
        return ret;
    };

    ll ans = 1;
    for(int i = 0; i < n; ++i) {
        if(!vis[i]) {
            cur.clear();
            make(i);
            col[cur[0]] = 1;
            ans *= 3ll * dfs(0, 1);
        }
    }

    printf("%lld", ans);
}
int main() {
    int t = 1;
    // scanf("%d",&t);
    while(t--)
        solve(), puts("");
}
