#include using namespace std; template< typename G > struct DoublingLowestCommonAncestor { const int LOG; vector< int > dep; const G &g; vector< vector< int > > table; DoublingLowestCommonAncestor(const G &g) : g(g), dep(g.size()), LOG(32 - __builtin_clz(g.size())) { table.assign(LOG, vector< int >(g.size(), -1)); } void dfs(int idx, int par, int d) { table[0][idx] = par; dep[idx] = d; for(auto &to : g[idx]) { if(to != par) dfs(to, idx, d + 1); } } void build() { dfs(0, -1, 0); for(int k = 0; k + 1 < 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(dep[u] > dep[v]) swap(u, v); for(int i = LOG - 1; i >= 0; i--) { if(((dep[v] - dep[u]) >> i) & 1) v = table[i][v]; } if(u == v) return u; for(int i = LOG - 1; i >= 0; i--) { if(table[i][u] != table[i][v]) { u = table[i][u]; v = table[i][v]; } } return table[0][u]; } }; #include #include #include template struct EularTour{ std::vector> tree; std::vector tourArr; std::vector begin; std::vector end; size_t step; EularTour() = delete; EularTour(const std::vector>& Graph, const size_t GraphSize) : tree(Graph), step(0){ begin.resize(GraphSize); end.resize(GraphSize); //visited.assign(GraphSize, false); } void makeTour(size_t v, size_t par=1e9){ begin[v] = step; tourArr.emplace_back(v); step++; for(GraphType& next : tree[v]){ if(next == par) continue; makeTour(next, step, v); tourArr.emplace_back(v); step++; } end[v] = step; } bool isChild(GraphType x, GraphType y){ if(begin[x] < begin[y] && begin[y] < end[x]) return true; return false; } }; vector wei; vector d; void dfs(vector>>& g, int v, int p){ for(auto e : g[v]){ if(e.first == p) continue; wei[e.first] += (e.second + wei[v]); d[e.first] = d[v]+1; dfs(g, e.first, v); } } int main(){ int N; cin >> N; vector> G(N); vector>> g(N); wei.assign(N, 0); d.assign(N, 0); for(int i = 0; i < N-1; i++){ int u,v,w; cin >> u >> v >> w; G[u].emplace_back(v); G[v].emplace_back(u); g[u].emplace_back(make_pair(v,w)); g[v].emplace_back(make_pair(u,w)); } dfs(g, 0, -1); DoublingLowestCommonAncestor>> lca(G); lca.build(); EularTour et(G, G.size()); int Q, x, y, z; cin >> Q; for(int i = 0; i < Q; i++){ cin >> x >> y >> z; vector> v = {{d[x],x}, {d[y], y}, {d[z], z}}; sort(v.rbegin(), v.rend()); int W = 0; x = v[0].second; y = v[1].second; z = v[2].second; if(et.isChild(x, z)) swap(y, z); int a = lca.query(x, y); int p = (wei[x] - wei[a]) + (wei[y] - wei[a]); W += p; int b = lca.query(a, z); int q = (wei[a] - wei[b]) + (wei[z] - wei[b]); W += q; cout << W << endl; } }