#include #include #include using namespace std; typedef long long LL; const int N = 100010, M = 2 * N, L = 20; LL sum[N][L]; int n, q, h[N], e[M], ne[M], w[M], idx, anc[N][L], dep[N]; void Add(int x, int y, int z) { e[idx] = y, w[idx] = z, ne[idx] = h[x], h[x] = idx++; } void DFS(int u, int p, int in_w) { anc[u][0] = p, sum[u][0] = in_w, dep[u] = dep[p] + 1; for (int i = 1; i < L; ++i) { anc[u][i] = anc[anc[u][i - 1]][i - 1]; sum[u][i] = sum[u][i - 1] + sum[anc[u][i - 1]][i - 1]; } for (int i = h[u]; i != -1; i = ne[i]) { int v = e[i]; if (v == p) continue; DFS(v, u, w[i]); } } int LCA(int u, int v) { if (dep[u] < dep[v]) swap(u, v); int d = dep[u] - dep[v]; for (int i = 0; i < L; ++i) { if (d >> i & 1) { u = anc[u][i]; } } if (u == v) return u; for (int i = L - 1; i >= 0; --i) { if (anc[u][i] != anc[v][i]) { u = anc[u][i]; v = anc[v][i]; } } return anc[u][0]; } LL Dist(int u, int v) { if (dep[u] < dep[v]) swap(u, v); LL ret = 0LL; for (int i = L - 1; i >= 0; --i) { if (anc[u][i] && dep[anc[u][i]] > dep[v]) { ret += sum[u][i]; u = anc[u][i]; } } return ret + sum[u][0]; } int main() { // freopen("lucky.in", "r", stdin); // freopen("lucky.out", "w", stdout); scanf("%d", &n); memset(h, -1, sizeof(h)); for (int i = 1, x, y, z; i <= n - 1; ++i) { scanf("%d%d%d", &x, &y, &z); ++x, ++y; Add(x, y, z), Add(y, x, z); } DFS(1, 0, 0); scanf("%d", &q); while (q--) { int x, y, z; scanf("%d%d%d", &x, &y, &z); ++x, ++y, ++z; int lcaxy = LCA(x, y), lcayz = LCA(y, z), lcazx = LCA(z, x); // LL ans = Dist(x, lcaxy) + Dist(lcaxy, y) + Dist(y, lcayz) + Dist(lcayz, z) + Dist(z, lcazx) + Dist(lcazx, x); LL ans = Dist(x, lcaxy); ans += Dist(lcaxy, y); ans += Dist(y, lcayz); ans += Dist(lcayz, z); ans += Dist(z, lcazx); ans += Dist(lcazx, x); printf("%lld\n", ans / 2); } return 0; }