#include #include #include #include #include #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; using ll = long long; using P = pair; constexpr int INF = 1001001001; // constexpr int mod = 1000000007; constexpr int mod = 998244353; template inline bool chmax(T& x, T y){ if(x < y){ x = y; return true; } return false; } template inline bool chmin(T& x, T y){ if(x > y){ x = y; return true; } return false; } template struct Edge{ int to; T cost; Edge() = default; Edge(int to, T 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 < (int)g[from].size(); ++i){ int to = g[from][i].to; T 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 < (int)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); v = get(v, depth[v] - depth[u]); 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 get(int v, int x){ if(x <= 0) return v; for(int i = ub_log - 1; i >= 0; --i){ if(x >> i & 1) v = table[i][v]; } return v; } 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; } }; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N; vector>> g(N); for(int i = 1; i < N; ++i){ int a, b, c; cin >> a >> b >> c; --a, --b; g[a].emplace_back(b, c); g[b].emplace_back(a, c); } CostLCA lca(g); lca.build(); cin >> Q; for(int q = 0; q < Q; ++q){ int s, t; cin >> s >> t; --s, --t; cout << lca.dist(s, t) << '\n'; } return 0; }