// ROOT : DRAGON3012009
#include <bits/stdc++.h>
using namespace std;// anh VBuongw BẮT EM NÔP THƯ Ạ , TẠIH BẠN Ở NHÀ
using ll = long long;
const int MAXN = 200000 + 5;
const int KMAX = 10; // k <= 10
const int TOPSZ = KMAX + 1; // lưu top 11 (k+1)
int T;
int bpar[MAXN], H[MAXN], V[MAXN];
ll sumVal[MAXN];
// topH[i][j]: j-th lớn nhất (0-based) của các h trên đường i->1, j < topSz[i]
int topH[MAXN][TOPSZ];
int topSz[MAXN];
int Q;
int rq[MAXN], kq[MAXN];
ll ans[MAXN];
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> T;
// Node 1 là gốc
for(int i = 2; i <= T; ++i){
int b, h, v; cin >> b >> h >> v;
bpar[i] = b; H[i] = h; V[i] = v;
}
// sumVal & topH
sumVal[1] = 0;
topSz[1] = 0;
for(int j = 0; j < TOPSZ; ++j) topH[1][j] = -1;
for(int i = 2; i <= T; ++i){
int p = bpar[i];
sumVal[i] = sumVal[p] + V[i];
// copy top của cha vào buffer
int s = topSz[p];
int buf[TOPSZ + 1]; // cho phép dư 1 để chèn rồi cắt xuống 11
for(int j = 0; j < s; ++j) buf[j] = topH[p][j];
// chèn H[i] vào buf sao cho giảm dần
int pos = 0;
while(pos < s && buf[pos] >= H[i]) ++pos;
// dịch sang phải
for(int j = min(s, TOPSZ); j > pos; --j) buf[j] = buf[j-1];
buf[pos] = H[i];
int ns = min(s + 1, TOPSZ);
for(int j = 0; j < ns; ++j) topH[i][j] = buf[j];
topSz[i] = ns;
// phần còn lại (nếu có) không cần set
}
cin >> Q;
vector<pair<int,int>> bucketQ[KMAX+1]; // (r, id)
for(int i = 0; i < Q; ++i){
int r, k; cin >> r >> k;
rq[i] = r; kq[i] = k;
bucketQ[k].push_back({r, i});
}
// Xử lý cho từng k
vector<pair<int,ll>> items; // (f_k(i), sumVal[i])
items.reserve(T);
for(int k = 0; k <= KMAX; ++k){
// chuẩn bị items cho k
items.clear();
items.reserve(T);
for(int i = 1; i <= T; ++i){
int fk = -1;
if(topSz[i] > k) fk = topH[i][k]; // (k+1)-th lớn nhất là index k
items.push_back({fk, sumVal[i]});
}
sort(items.begin(), items.end(), [](const auto& a, const auto& b){
if(a.first != b.first) return a.first < b.first;
return a.second < b.second; // tie-break không quan trọng
});
// xử lý các truy vấn có đúng k
auto &B = bucketQ[k];
if(B.empty()) continue;
sort(B.begin(), B.end()); // sort theo r tăng
ll curMax = 0; // v >= 0 => sumVal >= 0, nên init = 0 là đúng
int ptr = 0;
for(auto [r, id] : B){
while(ptr < (int)items.size() && items[ptr].first <= r){
curMax = max(curMax, items[ptr].second);
++ptr;
}
ans[id] = curMax;
}
}
// in kết quả
for(int i = 0; i < Q; ++i) cout << ans[i] << "\n";
return 0;
}