#include "bits/stdc++.h" #define REP(i, n) for(int i = 0; i < int(n); i++) #define FOR(i,n,m) for(int i = int(n); i < int(m); i++) using namespace std; typedef long long ll; struct Edge { int to, cost; }; // 最近共通祖先(Doubling) // verrify : https://onlinejudge.u-aizu.ac.jp/problems/GRL_5_C // struct LowestCommonAncestor { private: int n; int log; vector> parent; vector dep; vector dis; // root からの距離 void dfs(const vector> &G, int v, int p, int d, int di) { parent[0][v] = p; dep[v] = d; dis[v] = di; for (Edge e : G[v]) { if (e.to != p) dfs(G, e.to, v, d + 1,di + e.cost); } } public: LowestCommonAncestor(const vector> &G, int root = 0) { build(G, root); } void build(const vector> &G, int root = 0) { n = G.size(); log = log2(n) + 1; parent.resize(log, vector(n)); dep.resize(n); dis.resize(n); dfs(G, root, -1, 0, 0); for (int k = 0; k + 1 < log; k++) { for (int v = 0; v < G.size(); v++) { if (parent[k][v] < 0) { parent[k + 1][v] = -1; } else { parent[k + 1][v] = parent[k][parent[k][v]]; } } } } int depth(int v) { return dep[v]; } // O(logN) int lca(int u, int v) { if (dep[u] > dep[v]) swap(u, v); REP(k, log) if ((dep[v] - dep[u]) >> k & 1) v = parent[k][v]; if (u == v) return u; for (int k = log - 1; k >= 0; k--) { if (parent[k][u] != parent[k][v]) { u = parent[k][u]; v = parent[k][v]; } } return parent[0][u]; } int dist(int u, int v) { return dis[u] + dis[v] - 2 * dis[lca(u, v)]; } }; int main() { int n; cin >> n; vector> G(n); REP(i, n-1) { int a, b, c; scanf("%d %d %d", &a, &b, &c); G[a].push_back({b,c}); G[b].push_back({a,c}); } LowestCommonAncestor lca(G); int q; cin >> q; REP(i, q) { int a, b, c; scanf("%d %d %d", &a, &b, &c); ll sum = 0; sum += lca.dist(a, b); sum += lca.dist(b, c); sum += lca.dist(c, a); cout << sum / 2 << endl; } return 0; }