#include using namespace std; #define REP(i,n) for(int i=0; i<(int)(n); i++) void dfs(int v, int p, int d, long long s, vector &par, vector &depth, vector &sum, vector > > &edges) { par[v] = p; depth[v] = d; sum[v] = s; for (auto &pr: edges[v]) { int w, cost; tie(w, cost) = pr; if (w == p) continue; dfs(w, v, d+1, s + cost, par, depth, sum, edges); } } int lca(int v, int w, const vector > &par, const vector &depth) { if (depth[w] > depth[v]) swap(v, w); for (int i = 0; i < par.size(); i++) { int d = depth[v] - depth[w]; if (d & 1 << i) { v = par[i][v]; } } if (v == w) return v; for (int i = par.size() - 1; i >= 0; i--) { if (par[i][v] != par[i][w]) { v = par[i][v]; w = par[i][w]; } } return par[0][v]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector > > edges(n); REP (i, n-1) { int v, w, c; cin >> v >> w >> c; --v, --w; edges[v].emplace_back(w, c); edges[w].emplace_back(v, c); } vector par(n); vector depth(n); vector sum(n); dfs(0, -1, 0, 0, par, depth, sum, edges); vector > dp(18, vector(n)); REP (i, n) dp[0][i] = par[i]; for (int i = 1; i < 18; i++) { REP (j, n) { int tmp = dp[i-1][j]; if (tmp == -1) dp[i][j] = -1; else dp[i][j] = dp[i-1][tmp]; } } int Q; cin >> Q; while (Q--) { int s, t; cin >> s >> t; --s, --t; int w = lca(s, t, dp, depth); long long ret = sum[s] + sum[t] - 2 * sum[w]; cout << ret << endl; } return 0; }