#include #include #define rep(i, n) for (int i = 0; i < (int)(n); i++) using namespace atcoder; using ll = long long; const ll MOD1 = 1000000007LL; const ll MOD2 = 998244353LL; using namespace std; const vector> dpos4 = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; // const vector> dpos8 = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; template bool chmax(T &a, const T& b) { if (a < b) { a = b; // aをbで更新 return true; } return false; } // aよりもbが小さいならばaをbで更新する // (更新されたならばtrueを返す) template bool chmin(T &a, const T& b) { if (a > b) { a = b; // aをbで更新 return true; } return false; } int main() { int N; cin >> N; vector> edges(N); rep(i, N - 1){ int a, b; cin >> a >> b; edges[a].push_back(b); edges[b].push_back(a); } vector U(N); rep(i, N) cin >> U[i]; vector depth(N, 0); vector money(N, 0); vector> parent(20, vector(N, 0)); money[0] = U[0]; auto dfs = [&](auto self, int fr, int prev=-1) -> void { for(auto to: edges[fr]){ if(to == prev) continue; depth[to] = depth[fr] + 1; money[to] = money[fr] + U[to]; parent[0][to] = fr; self(self, to, fr); } }; dfs(dfs, 0); for(int i = 1; i < 20; i++){ rep(j, N){ parent[i][j] = parent[i - 1][parent[i - 1][j]]; } } auto get_lca = [&](int a, int b) { if(depth[a] < depth[b]) swap(a, b); int d = depth[a] - depth[b]; rep(i, 20){ if((d >> i) % 2 == 1) a = parent[i][a]; } if(a == b) return a; for(int i = 19; i >= 0; i--){ if(parent[i][a] == parent[i][b]) continue; a = parent[i][a]; b = parent[i][b]; } return parent[0][a]; }; auto calc = [&](int a, int b){ int p = get_lca(a, b); ll ans = money[a] + money[b] - 2 * money[p] + U[p]; return ans; }; int M; cin >> M; ll ans = 0; rep(i, M){ int a, b, c; cin >> a >> b >> c; ans += calc(a, b) * c; } cout << ans << endl; return 0; }