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

const ll MAX_N = 200'000;

ll N, P, Q, U, D;
vector<ll> G[MAX_N];
ll in[MAX_N], out[MAX_N];
vector<vector<ll>> mat;

ll cnt = 0;

void dfs(ll u, ll d) {
  in[u] = cnt++;
  mat[d].push_back(in[u]);
  for (auto v : G[u]) {
    dfs(v, d + 1);
  }
  out[u] = cnt++;
}

int main() {
  cin >> N;
  mat = vector<vector<ll>>(N);
  for (ll i = 1; i < N; ++i) {
    cin >> P;
    G[P - 1].push_back(i);
  }
  dfs(0, 0);
  cin >> Q;
  while (Q--) {
    cin >> U >> D;
    --U;
    vector<ll> &v = mat[D];
    cout << lower_bound(v.begin(), v.end(), out[U])
                - lower_bound(v.begin(), v.end(), in[U])
         << endl;
  }
}
#include <iostream>
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;

class BIT {
public:
	int size_ = 1;
	vector<long long> dat;

	void init(int sz) {
		size_ = sz + 2;
		dat.resize(size_ + 2, 0);
	}
	void add(int pos, long long x) {
		pos++;
		while (pos <= size_) {
			dat[pos] += x;
			pos += (pos & -pos);
		}
	}
	long long sum(int pos) {
		long long s = 0; pos++;
		while (pos >= 1) {
			s += dat[pos];
			pos -= (pos & -pos);
		}
		return s;
	}
};

long long N;
long long A[1 << 18];
long long B[1 << 18];
long long C[1 << 18];
long long Answer = 0;

int main() {
	cin >> N;
	for (int i = 1; i <= N; i++) cin >> A[i];
	for (int i = 1; i <= N; i++) cin >> B[i];

	vector<pair<long long, int>> vec1, vec2;
	for (int i = 1; i <= N; i++) vec1.push_back(make_pair(A[i] + i, i));
	for (int i = 1; i <= N; i++) vec2.push_back(make_pair(B[i] + i, i));
	sort(vec1.begin(), vec1.end());
	sort(vec2.begin(), vec2.end());
	for (int i = 0; i < N; i++) {
		C[vec2[i].second] = vec1[i].second;
		if (vec1[i].first != vec2[i].first) {
			cout << "-1" << endl;
			return 0;
		}
	}

	BIT Z;
	Z.init(N + 2);
	for (int i = 1; i <= N; i++) {
		Answer += Z.sum(N + 1) - Z.sum(C[i]);
		Z.add(C[i], 1);
	}
	cout << Answer << endl;
	return 0;
}