#include #define MAX_SIZE 100000 #define LOG_SIZE 17 using namespace std; typedef long long ll; typedef pair ii; vector adjList[MAX_SIZE]; int lcs[MAX_SIZE][LOG_SIZE], lvl[MAX_SIZE]; ll tot[MAX_SIZE]; void dfs(int cur, ll sum, int p, int cd) { tot[cur] = sum; lcs[cur][0] = p; lvl[cur] = cd; for (auto nxt : adjList[cur]) if (nxt.first != p) dfs(nxt.first, sum + nxt.second, cur, cd + 1); } int findParent(int a, int b) { if (lvl[a] > lvl[b]); swap(a, b); for (int ctr1 = 0; ctr1 < LOG_SIZE; ++ctr1) if ((lvl[b] - lvl[a]) & (1 << ctr1)) b = lcs[b][ctr1]; if (a == b) return a; for (int ctr1 = lvl[a] - 1; ctr1 >= 0; --ctr1) if (lcs[a][ctr1] != lcs[b][ctr1]) a = lcs[a][ctr1], b = lcs[b][ctr1]; return lcs[a][0]; } ll pathSum(int a, int b, int p) { return tot[a] + tot[b] - 2 * tot[p]; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, q; cin >> n; int a, b, c; for (int ctr1 = 1; ctr1 < n; ++ctr1) { cin >> a >> b >> c; adjList[a].push_back({b, c}); adjList[b].push_back({a, c}); } dfs(0, 0, 0, 0); for (int ctr1 = 1; ctr1 < LOG_SIZE; ++ctr1) for (int ctr2 = 0; ctr2 < n; ++ctr2) lcs[ctr2][ctr1] = lcs[lcs[ctr2][ctr1 - 1]][ctr1 - 1]; cin >> q; for (int ctr1 = 0; ctr1 < q; ++ctr1) { cin >> a >> b >> c; int ab = findParent(a, b); int bc = findParent(b, c); int ac = findParent(a, c); int f, s, t; if (ab == bc) f = a, s = c, t = b; if (bc == ac) f = a, s = b, t = c; if (ab == ac) f = b, s = c, t = a; int smallTree = findParent(f, s); int bigTree = findParent(smallTree, t); cout << pathSum(f, s, smallTree) + pathSum(smallTree, t, bigTree) << "\n"; } return 0; }