#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define chmax(x, y) x = max(x, y) #define chmin(x, y) x = min(x, y) typedef long long ll; typedef uint64_t ull; typedef pair P; typedef pair Pid; typedef pair Pdi; typedef pair Pl; typedef pair Pll; typedef pair> PP; typedef pair PPi; constexpr double PI = 3.1415926535897932; // acos(-1) constexpr double EPS = 1e-9; constexpr int INF = 1001001001; constexpr int mod = 1e+9 + 7; // constexpr int mod = 998244353; struct edge{ int to; ll cost; edge() = default; edge(int to, ll cost) : to(to), cost(cost) {} }; struct LCA{ using G = vector>; vector depth; vector> table; vector costs; const G& g; int ub_log; void dfs(int from = 0, int p = -1){ if(p == -1){ depth[from] = 0; costs[from] = 0; } table[0][from] = p; for(int i = 0; i < g[from].size(); ++i){ int to = g[from][i].to; ll cost = g[from][i].cost; if(to == p) continue; depth[to] = depth[from] + 1; costs[to] = costs[from] + cost; dfs(to, from); } } void build(){ for(int k = 0; k + 1 < ub_log; ++k){ for(int i = 0; i < g.size(); ++i){ if(table[k][i] == -1) table[k + 1][i] = -1; else table[k + 1][i] = table[k][table[k][i]]; } } } LCA (const G& g) : g(g), ub_log(32 - __builtin_clz(g.size())) { depth.resize(g.size()); costs.resize(g.size()); table.assign(ub_log, vector(g.size())); dfs(); build(); } int lca(int u, int v){ if(depth[u] > depth[v]) swap(u, v); for(int k = ub_log - 1; k >= 0; --k){ if(((depth[v] - depth[u]) >> k) & 1) v = table[k][v]; } if(u == v) return u; for(int k = ub_log - 1; k >= 0; --k){ if(table[k][u] != table[k][v]){ u = table[k][u]; v = table[k][v]; } } return table[0][u]; } ll get_dist(int u, int v){ return costs[u] + costs[v] - costs[lca(u, v)] * 2; } void print(){ for(int k = 0; k < ub_log; ++k){ for(int i = 0; i < g.size(); ++i){ cerr << table[k][i] << " "; } cerr << "\n"; } } void cprint(){ for(int i = 0; i < g.size(); ++i) cerr << costs[i] << " "; cerr << "\n"; } }; int n; vector> graph; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n; graph.resize(n); for(int i = 0; i < n - 1; ++i){ int u, v; ll w; cin >> u >> v >> w; graph[u].emplace_back(edge(v, w)); graph[v].emplace_back(edge(u, w)); } LCA l(graph); int q; cin >> q; for(int i = 0; i < q; ++i){ int x, y, z; cin >> x >> y >> z; ll ans = l.get_dist(x, y) + l.get_dist(y, z) + l.get_dist(z, x); ans /= 2; cout << ans << "\n"; } }