#include using namespace std; vector>> G; vector> parent; vector dist, height; int M = 1; void dfs(int v, int p) { for(auto [nv, c] : G[v]) { if(nv == p) continue; parent[0][nv] = v; height[nv] = height[v] + 1; dist[nv] = dist[v] + c; dfs(nv, v); } } int lca(int u, int v) { if(height[u] < height[v]) swap(u, v); int k = height[u] - height[v]; for(int lv = 0; (1 << lv) <= k; lv++) { if((k >> lv) & 1) u = parent[lv][u]; } if(u == v) return u; for(int lv = M - 1; lv >= 0; lv--) { if(parent[lv][u] != parent[lv][v]) { u = parent[lv][u]; v = parent[lv][v]; } } return parent[0][u]; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int N; cin >> N; G.assign(N, vector>(0)); while((1 << M) < N) M++; parent.assign(M, vector(N, -1)); dist.assign(N, 0); height.assign(N, 0); for(int i = 0; i < N - 1; i++) { int a, b, c; cin >> a >> b >> c; a--; b--; G[a].push_back({b, c}); G[b].push_back({a, c}); } dfs(0, -1); for(int lv = 1; lv < M; lv++) { for(int i = 0; i < N; i++) { parent[lv][i] = parent[lv - 1][parent[lv - 1][i]]; } } int Q; cin >> Q; while(Q--) { int s, t; cin >> s >> t; s--; t--; cout << dist[s] + dist[t] - 2 * dist[lca(s, t)] << "\n"; } return 0; }