#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, cost; Edge() = default; Edge(int to, int cost) : to(to), cost(cost) {} }; template struct CostLCA{ using G = vector>; const int ub_log; vector depth; vector costs; const G& g; vector> table; CostLCA(const G& g) : g(g), depth(g.size()), costs(g.size()), ub_log(32 - __builtin_clz(g.size())){ table.assign(ub_log, vector(g.size(), -1)); } void dfs(int from, int par = -1, int dep = 0, T sum = 0){ table[0][from] = par; depth[from] = dep; costs[from] = sum; for(int i = 0; i < g[from].size(); ++i){ int to = g[from][i].to, cost = g[from][i].cost; if(to != par) dfs(to, from, dep + 1, sum + cost); } } void build(int root = 0){ dfs(root); for(int k = 0; k + 1 < ub_log; ++k){ for(int i = 0; i < table[k].size(); ++i){ if(table[k][i] == -1) table[k + 1][i] = -1; else table[k + 1][i] = table[k][table[k][i]]; } } } int query(int u, int v){ if(depth[u] > depth[v]) swap(u, v); for(int i = ub_log - 1; i >= 0; --i){ if(((depth[v] - depth[u]) >> i) & 1) v = table[i][v]; } if(u == v) return u; for(int i = ub_log - 1; i >= 0; --i){ if(table[i][u] != table[i][v]){ u = table[i][u]; v = table[i][v]; } } return table[0][u]; } int length(int u, int v){ int lca = query(u, v); return depth[u] + depth[v] - depth[lca] * 2; } T dist(int u, int v){ int lca = query(u, v); return costs[u] + costs[v] - costs[lca] * 2; } void print(){ for(int k = 0; k + 1 < ub_log; ++k){ for(int i = 0; i < table[k].size(); ++i){ cerr << table[k][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, w; cin >> u >> v >> w; graph[u].emplace_back(Edge(v, w)); graph[v].emplace_back(Edge(u, w)); } CostLCA l(graph); l.build(); int q; cin >> q; for(int i = 0; i < q; ++i){ int x, y, z; cin >> x >> y >> z; ll ans = l.dist(x, y) + l.dist(y, z) + l.dist(z, x); ans /= 2; cout << ans << "\n"; } }