//#include #include using namespace std; typedef long long ll; typedef pair p; const int INF = 1e9; const ll LINF = ll(1e18) + 1; const int MOD = 1000000007; const int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0}; const int Dx[8] = {0, 1, 1, 1, 0, -1, -1, -1}, Dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; #define yes cout << "Yes" << endl #define YES cout << "YES" << endl #define no cout << "No" << endl #define NO cout << "NO" << endl #define rep(i, n) for (int i = 0; i < n; i++) #define ALL(v) v.begin(), v.end() #define debug(v) \ cout << #v << ":"; \ for (auto x : v) \ { \ cout << x << ' '; \ } \ cout << endl; template bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template bool chmin(T &a, const T &b) { if (b < a) { a = b; return 1; } return 0; } //cout< a; template struct edge { int src, to; T cost; edge(int to, T cost) : src(-1), to(to), cost(cost) {} edge(int src, int to, T cost) : src(src), to(to), cost(cost) {} edge &operator=(const int &x) { to = x; return *this; } operator int() const { return to; } }; template using Edges = vector>; template using WeightedGraph = vector>; using UnWeightedGraph = vector>; template using Matrix = vector>; template struct DoublingLowestCommonAncestor { const int LOG; vector dep; const G &g; vector> table; DoublingLowestCommonAncestor(const G &g) : g(g), dep(g.size()), LOG(32 - __builtin_clz(g.size())) { table.assign(LOG, vector(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]; } }; vector>> v; vector dep; void dfs(int k,int prev,ll d){ dep[k]=d; rep(i,v[k].size()){ if(v[k][i].first==prev)continue; dfs(v[k][i].first,k,d+v[k][i].second); } } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> n; v.resize(n); UnWeightedGraph g(n); for (int i = 0; i < n-1; i++) { ll temp,temp1,temp2; cin >> temp>>temp1>>temp2; v[temp].push_back(make_pair(temp1,temp2)); v[temp1].push_back(make_pair(temp,temp2)); g[temp].push_back(temp1); g[temp1].push_back(temp); } dep.resize(n); dfs(0,-1,0); DoublingLowestCommonAncestor lca(g); lca.build(); int q; cin>>q; vector ans; while(q--){ ll x,y,z; cin>>x>>y>>z; ll sum=0; int temp=lca.query(x,y); sum+=dep[x]-dep[temp]; sum+=dep[y]-dep[temp]; temp=lca.query(z,y); sum+=dep[z]-dep[temp]; sum+=dep[y]-dep[temp]; temp=lca.query(x,z); sum+=dep[x]-dep[temp]; sum+=dep[z]-dep[temp]; ans.push_back(sum/2); } rep(i,ans.size()) cout << ans[i] << "\n"; }