#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define visit asdf
const int N=4e5+5;
const int M=4e5+5;

int n,m,ans;
int a[N],b[N];
int indeg[M];
vector<int> v[M];
bool visit[N];
queue<int> q;

int match(int x)
{
	for(int i=0;i<v[x].size();i++)
		if(!visit[v[x][i]]) return v[x][i];
	return 4e5+1;
}

int main()
{
	cin>>n; m=4e5;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i]>>b[i];
		indeg[a[i]]++; v[a[i]].pb(i);
		indeg[b[i]]++; v[b[i]].pb(i);
	}
	for(int i=1;i<=n;i++)
		if(indeg[a[i]]==1 || indeg[b[i]]==1) q.push(i),visit[i]=1;
	for(int i=1;i<=m;i++)
		if(indeg[i]) ans++;
	
	while(!q.empty())
	{
		int x=q.front(); q.pop();
		if(indeg[a[x]]==1 && indeg[b[x]]==1) ans--;
		if(indeg[a[x]]==1) if(--indeg[b[x]]==1) q.push(match(b[x])),visit[match(b[x])]=1;
		if(indeg[b[x]]==1) if(--indeg[a[x]]==1) q.push(match(a[x])),visit[match(a[x])]=1;
	}
	cout<<ans<<'\n';
	
	return 0;
}
#include <bits/stdc++.h>
//#include <atcoder/all>
#ifndef LOCAL
#pragma GCC target("arch=skylake-avx512")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif
using namespace std;

typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-12;
static const double PI = acos(-1.0);

#define FOR(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(a) (a).begin(), (a).end()
#ifdef LOCAL
#define dbg(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl
#else
#define dbg(x) true
#endif

map<ll, vector<pair<ll, ll>>> m;
vector<vector<ll>> graph;
vector<ll> ans;

map<ll, ll> dfs(ll i, ll depth) {
  map<ll, ll> ret;
  for (auto j : graph[i]) {
    auto x = dfs(j, depth + 1);
    if (ret.size() < x.size()) {
      ret.swap(x);
    }
    for (auto [k, v] : x) {
      ret[k] += v;
    }
  }
  ret[depth]++;
  for (auto [num, d] : m[i]) {
    ans[num] = ret[d];
  }
  return (ret);
}

void solve(long long N, std::vector<long long> P, long long Q, std::vector<long long> U, std::vector<long long> D) {
  ans.resize(Q);
  REP(i, Q) {
    m[U[i]].push_back(make_pair(i, D[i]));
  }
  graph.resize(N);
  FOR(i, 1, N) {
    graph[P[i - 1]].push_back(i);
  }
  dfs(0, 0);
  REP(i, Q) {
    cout << ans[i] << endl;
  }
}

int main() {
  long long N;
  std::scanf("%lld", &N);
  std::vector<long long> P(N - 2 + 1);
  for (int i = 0; i < N - 2 + 1; i++) {
    std::scanf("%lld", &P[i]);
    P[i]--;
  }
  long long Q;
  std::scanf("%lld", &Q);
  std::vector<long long> U(Q);
  std::vector<long long> D(Q);
  for (int i = 0; i < Q; i++) {
    std::scanf("%lld", &U[i]);
    std::scanf("%lld", &D[i]);
    U[i]--;
  }
  solve(N, std::move(P), Q, std::move(U), std::move(D));
  return 0;
}
