#include<bits/stdc++.h>
#define ll long long
#define fr(i,j,k) for(int i=j;i<k;i++)
#define f(n) fr(i,0,n)
#define f1(n) fr(i,1,n+1)
#define pb push_back
#define F first
#define S second
#define all(x) x.begin(), x.end()
const int mod = 1e9+7;
using namespace std;
vector<int>v[200005];
vector<int>g[200005];
int dep[200005];
int in[200005], out[200005];
int stamp;
void dfs(int now, int pre) {
    in[now] = ++stamp;
    v[dep[now]].pb(stamp);
    for (auto &i : g[now]) {
        if (i == pre) {
            continue;
        }
        dep[i] = dep[now] + 1;
        dfs(i, now);
    }
    out[now] = stamp;
}
void solve() {
    int n;
    cin >> n;
    for (int i = 2 ; i <= n ; i++) {
        int x;
        cin >> x;
        g[x].pb(i);
    }
    dfs(1, 0);
    int q;
    cin >> q;
    while (q--) {
        int x, y;
        cin >> x >> y;
        
        cout << upper_bound(v[y].begin(), v[y].end(),out[x]) - lower_bound(v[y].begin(), v[y].end(),in[x]) << '\n';
    }
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    //cin >> t;
    while (t--) {
        solve();
    }
}
#include <iostream>
#include <vector>
using namespace std;
const int INF = (1u<<31) - 1;

int main() {
	int n;
	cin >> n;
	long long max_thr = INF, min_thr = -INF;
	long long max_v = INF, min_v = -INF;
	for (int i = 0; i < n; i++) {
		long long a, t;
		cin >> a >> t;
		if (t == 1) {
			max_v += a;
			min_v += a;
		} else if (t == 2) {
			if (a > min_v) {
				min_thr += a - min_v;
				min_v += a - min_v;
				if (max_thr < min_thr) {
					max_thr = min_thr;
					max_v = min_v;
				}
			}
		} else {
			if (a < max_v) {
				max_thr -= max_v - a;
				max_v -= max_v - a;
				if (max_thr < min_thr) {
					min_thr = max_thr;
					min_v = max_v;
				}
			}
		}
	}
	int Q;
	cin >> Q;
	for (int q = 0; q < Q; q++) {
		long long x;
		cin >> x;
		long long ans;
		if (x <= min_thr) {
			ans = min_v;
		} else if (x >= max_thr) {
			ans = max_v;
		} else {
			ans = min_v + (x - min_thr);
		}
		cout << ans << endl;
	}
	return 0;
}