import std.conv, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.container, std.math, std.numeric, std.range, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } real readReal() { return readToken.to!real; } void chmin(T)(ref T t, in T f) { if (t > f) t = f; } void chmax(T)(ref T t, in T f) { if (t < f) t = f; } int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(as.length); for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; } int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a < val)); } int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); } enum LIM_LOGN = 17; int N; int[] A, B; long[] U; int M; int[] S, T; long[] C; int[][] G; int[][] par; int[] dep; void dfs(int u, int p, int d) { par[0][u] = p; dep[u] = d; foreach (v; G[u]) { if (v != p) { dfs(v, u, d + 1); } } } void main() { try { for (; ; ) { N = readInt(); A = new int[N - 1]; B = new int[N - 1]; foreach (i; 0 .. N - 1) { A[i] = readInt(); B[i] = readInt(); } U = new long[N]; foreach (u; 0 .. N) { U[u] = readLong(); } M = readInt(); S = new int[M]; T = new int[M]; C = new long[M]; foreach (m; 0 .. M) { S[m] = readInt(); T[m] = readInt(); C[m] = readLong(); } G = new int[][N]; foreach (i; 0 .. N - 1) { G[A[i]] ~= B[i]; G[B[i]] ~= A[i]; } par = new int[][](LIM_LOGN, N); dep = new int[N]; const rt = 0; dfs(rt, rt, 0); auto parCost = new long[][](LIM_LOGN, N); foreach (u; 0 .. N) { parCost[0][u] = (u == rt) ? 0 : U[u]; } foreach (e; 1 .. LIM_LOGN) { foreach (u; 0 .. N) { par[e][u] = par[e - 1][par[e - 1][u]]; parCost[e][u] = parCost[e - 1][par[e - 1][u]] + parCost[e - 1][u]; } } long ans; foreach (m; 0 .. M) { long cost; int u = S[m], v = T[m]; foreach_reverse (e; 0 .. LIM_LOGN) { if (dep[u] - (1 << e) >= dep[v]) { cost += parCost[e][u]; u = par[e][u]; } if (dep[v] - (1 << e) >= dep[u]) { cost += parCost[e][v]; v = par[e][v]; } } foreach_reverse (e; 0 .. LIM_LOGN) { if (par[e][u] != par[e][v]) { cost += parCost[e][u]; cost += parCost[e][v]; u = par[e][u]; v = par[e][v]; } } if (u != v) { cost += parCost[0][u]; cost += parCost[0][v]; u = par[0][u]; v = par[0][v]; } assert(u == v); cost += U[u]; ans += C[m] * cost; debug { writefln("%s %s: %s", S[m], T[m], cost); } } writeln(ans); } } catch (EOFException e) { } }