// https://atcoder.jp/contests/abc191/tasks/abc191_e
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define repr(i, n) for (int i = n - 1; i >= 0; i--)
#define ALL(x) x.begin(), x.end()
using str = string;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vll = vector<ll>;
using vvl = vector<vector<ll>>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

struct Graph {
    struct Edge {
        int from, to, cost;
    };
    int n;
    int INF;
    vector<vector<Edge>> adj_list;
    Graph(int _n) {
        n = _n;
        INF = 1e9;
        adj_list.resize(n, vector<Edge>(0));
    }
    void add(int from, int to, int cost) {
        adj_list[from].push_back({from, to, cost});
    }
    int dijkstra(int start) {
        int ans = INF;
        vector<int> dist(n, INF);
        dist[start] = 0;
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
        pq.push({dist[start], start});
        while (not pq.empty()) {
            int cur = pq.top().second;
            pq.pop();
            for (Edge e : adj_list[cur]) {
                if (dist[e.to] > dist[cur] + e.cost) {
                    dist[e.to] = dist[cur] + e.cost;
                    pq.push({dist[e.to], e.to});
                }
                if (e.to == start) {
                    ans = min(ans, dist[cur] + e.cost);
                }
            }
        }
        return ans == INF ? -1 : ans;
    }
};

int main() {
    int n, m;
    cin >> n >> m;
    Graph g(n);
    rep(i, m) {
        int a, b, c;
        cin >> a >> b >> c;
        a--; b--;
        g.add(a, b, c);
    }
    rep(i, n) {
        cout << g.dijkstra(i) << endl;
    }
}

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)

using std::cin;
using std::cout;
using std::vector;

const int N = 200005;

vector<int> to[N];
int dep[N];
int in[N];
int out[N];
int k;
vector<int> ls[N];

void dfs(int v, int d) {
	in[v] = k++;
	dep[v] = d;
	for (int u : to[v]) dfs(u, d + 1);
	out[v] = k;
}

int main() {
	int n;
	cin >> n;
	
	rep(i, n - 1) {
		int p;
		cin >> p;
		to[p - 1].push_back(i + 1);
	}
	
	dfs(0, 0);
	
	rep(i, n) ls[dep[i]].push_back(in[i]);
	rep(i, n) sort(ls[i].begin(), ls[i].end());
	
	int q;
	cin >> q;
	
	auto f = [&](int d, int r) {
		return lower_bound(ls[d].begin(), ls[d].end(), r) - ls[d].begin();
	};
	
	rep(qi, q) {
		int u, d;
		cin >> u >> d;
		--u;
		int ans = f(d, out[u]) - f(d, in[u]);
		cout << ans << '\n';
	}
	
	return 0;
}