import sys; input = sys.stdin.buffer.readline sys.setrecursionlimit(10**7) from collections import defaultdict con = 10 ** 9 + 7; INF = float("inf") from collections import deque def getlist(): return list(map(int, input().split())) class Graph(object): def __init__(self): self.graph = defaultdict(list) def __len__(self): return len(self.graph) def add_edge(self, a, b, w): self.graph[a].append((b, w)) class BFS(object): def __init__(self, graph, N, s): self.g = graph.graph self.Q = deque(); self.Q.append(s) self.depth = [INF] * N; self.depth[s] = 0 self.prev = [None] * N; self.prev[s] = -1 self.dist = [INF] * N; self.dist[s] = 0 #深さ、距離、親確定 while self.Q: v = self.Q.popleft() for i, w in self.g[v]: if self.depth[i] == INF: self.depth[i] = self.depth[v] + 1 self.dist[i] = self.dist[v] + w self.prev[i] = v self.Q.append(i) #ダブリング self.nex = [[0] * N for i in range(N.bit_length())] for i in range(N): self.nex[0][i] = self.prev[i] for i in range(1, N.bit_length()): for j in range(N): var = self.nex[i - 1][j] if var == -1: self.nex[i][j] = -1 else: self.nex[i][j] = self.nex[i - 1][var] def LCA(a, b, N, depth, nex): x, y = a, b #深さ揃え if depth[x] > depth[y]: x, y = y, x if depth[x] < depth[y]: dif = depth[y] - depth[x] X = dif.bit_length() for i in range(X): if dif & 1 == 1: y = nex[i][y] dif = dif >> 1 #深さ同じで一致するなら終了 if x == y: lca = x return lca #LCA計算 for i in range(N.bit_length() - 1, -1, -1): if nex[i][x] != nex[i][y]: x = nex[i][x]; y = nex[i][y] lca = nex[0][x] return lca #処理内容 def main(): N = int(input()) G = Graph() for i in range(N - 1): a, b, w = getlist() a -= 1; b -= 1 G.add_edge(a, b, w) G.add_edge(b, a, w) BF = BFS(G, N, 0) depth, nex, dist = BF.depth, BF.nex, BF.dist #頂点a-bの距離 Q = int(input()) for i in range(Q): a, b = getlist() a -= 1; b -= 1 dis = dist[a] + dist[b] - 2 * dist[LCA(a, b, N, depth, nex)] # print(depth[a], dist[b], 2 * depth[LCA(a, b, N, depth, nex)]) print(dis) if __name__ == '__main__': main()