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

#define F                   first
#define S                   second
#define int                 long long int
#define pb                  push_back
#define mp                  make_pair
#define pii                 pair<int,int>
#define vi                  vector<int>
#define mii                 map<int,int>
#define pqb                 priority_queue<int>
#define pqs                 priority_queue<int,vi,greater<int> >
#define mod                 1000000007
#define endl                '\n'
#define rep(i,a,b)            for(int i=a;i<b;i++)
#define db(...) __f(#__VA_ARGS__, __VA_ARGS__)

template <typename Arg1>
void __f(const char* name, Arg1&& arg1) { cout << name << " : " << arg1 << '\n'; }
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
	const char* comma = strchr(names + 1, ',');
	cout.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...);
}
void c_p_c()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
}
const int N = 2e5 + 10;
vi gr[N];
int ans = 0;
int st[N];
int et[N];
int tim = 0;
vi d[N];
void dfs(int cur, int depth) {
	st[cur] = tim ++;
	d[depth].pb(st[cur]);
	for (auto x : gr[cur]) {
		dfs(x, depth + 1);
	}
	et[cur] = tim;
}
void solve() {
	int n;
	cin >> n;
	rep(i, 2, n + 1) {
		int p;
		cin >> p;
		gr[p].pb(i);
	}
	dfs(1, 0);
	int q;
	cin >> q;
	while (q--) {
		int U, D;
		cin >> U >> D;
		int l = st[U];
		int r = et[U];

		int ans = lower_bound(d[D].begin(), d[D].end(), r) - lower_bound(d[D].begin(), d[D].end(), l);

		cout << ans << endl;
	}
}
int32_t main()
{
	c_p_c();
	int t = 1;
	//cin >> t;
	while (t--) {
		solve();
	}


	return 0;
}

#include <bits/stdc++.h>

#define int long long

using namespace std;



int32_t main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int N;
    cin >> N;

    set<int> st;

    for(int i = 0 ; i < N ; i++)
    {
    	int n;
    	cin >> n;
    	st.insert(n);
    }

    while(1)
    {
    	if(st.size() == 1)break;

    	int may = *(--st.end());
    	int men = *(st.begin());

    	st.erase(may);
    	st.insert(may-men);
    }

    cout << *st.begin() << '\n';

    return 0;
}