/** * @FileName a.cpp * @Author kanpurin * @Created 2020.06.26 00:41:03 **/ #include "bits/stdc++.h" using namespace std; typedef long long ll; struct LowestCommonAncestor { private: struct edge { int to,cost; edge(int to, int cost) : to(to), cost(cost) {} }; int n; int log; vector> parent; vector dep; vector> G; vector dis; void dfs(const vector> &G, int v, int p, int d, int di) { parent[0][v] = p; dep[v] = d; dis[v] = di; for (edge e : G[v]) { if (e.to != p) dfs(G, e.to, v, d + 1,di + e.cost); } } public: LowestCommonAncestor(int n) : n(n) { G.resize(n); } void add_edge(int from, int to, int cost) { G[from].push_back(edge(to,cost)); G[to].push_back(edge(from,cost)); } void build(int root = 0) { log = log2(n) + 1; parent.resize(log, vector(n)); dep.resize(n); dis.resize(n); dfs(G, root, -1, 0, 0); for (int k = 0; k + 1 < log; k++) { for (int v = 0; v < G.size(); v++) { if (parent[k][v] < 0) { parent[k + 1][v] = -1; } else { parent[k + 1][v] = parent[k][parent[k][v]]; } } } } int depth(int v) { return dep[v]; } int lca(int u, int v) { if (dep[u] > dep[v]) swap(u, v); for (int k = 0; k < log; k++) if ((dep[v] - dep[u]) >> k & 1) v = parent[k][v]; if (u == v) return u; for (int k = log - 1; k >= 0; k--) { if (parent[k][u] != parent[k][v]) { u = parent[k][u]; v = parent[k][v]; } } return parent[0][u]; } int dist(int u, int v) { return dis[u] + dis[v] - 2 * dis[lca(u, v)]; } }; int main() { int n;cin >> n; LowestCommonAncestor lca(n); for (int i = 0; i < n-1; i++) { int a,b,c;cin >> a >> b >> c;a--;b--; lca.add_edge(a,b,c); } lca.build(); int q;cin >> q; for (int i = 0; i < q; i++) { int s,t;cin >> s >> t; s--;t--; cout << lca.dist(s,t) << endl; } return 0; }