// KKGyak.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
using namespace std;
#include <iostream>
#include <map>
#include <set>
#include <unordered_set>
#include <vector>
#include <algorithm>
void DFS(vector<vector<int>>& graph, int beginnode, int num, vector<unordered_set<int>>& edgeCont) {
edgeCont[beginnode].insert(num);
for (auto g : graph[beginnode]) {
DFS(graph, g, num, edgeCont);
}
}
int main()
{
int a;
cin >> a;
vector<vector<int>> g1(a+1);
for (size_t i = 2; i < a+1; i++)
{
int b;
cin >> b;
g1[b].push_back(i);
}
int c;
cin >> c;
vector<vector<int>> g2(c + 1);
for (size_t i = 2; i < c + 1; i++)
{
int b;
cin >> b;
g2[b].push_back(i);
}
int d;
cin >> d;
vector<unordered_set<int>> edgeCont1(a+1);
vector<unordered_set<int>> edgeCont2(c+1);
vector<int> weights(d);
for (size_t i = 0; i < d; i++)
{
int v1, v2, w;
cin >> v1 >> v2 >> w;
weights[i] = w;
DFS(g1, v1, i, edgeCont1);
DFS(g2, v2, i, edgeCont2);
}
int q;
cin >> q;
for (size_t i = 0; i < q; i++)
{
int q1, q2;
cin >> q1 >> q2;
int res = 0;
for (auto query : edgeCont2[q2]) {
if (edgeCont1[q1].count(query) == 1) {
res += weights[query];
}
}
cout << res << "\n";
}
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file