import sys from collections import deque def main(): sys.setrecursionlimit(1 << 25) input = sys.stdin.read().split() ptr = 0 N = int(input[ptr]) ptr +=1 adj = [[] for _ in range(N+1)] edges = {} for _ in range(N-1): u = int(input[ptr]) v = int(input[ptr+1]) w = int(input[ptr+2]) ptr +=3 adj[u].append((v, w)) adj[v].append((u, w)) edges[(u, v)] = w edges[(v, u)] = w Q = int(input[ptr]) ptr +=1 queries = [] for _ in range(Q): x = int(input[ptr]) y = int(input[ptr+1]) ptr +=2 queries.append((x, y)) # Preprocess BFS for path finding def bfs_path(start, end): parent = {} visited = [False]*(N+1) q = deque() q.append(start) visited[start] = True parent[start] = None found = False while q: u = q.popleft() if u == end: found = True break for v, w in adj[u]: if not visited[v]: visited[v] = True parent[v] = u q.append(v) if not found: return [] path = [] current = end while current is not None: path.append(current) current = parent[current] path.reverse() return path for x, y in queries: path = bfs_path(x, y) if not path: print(-1) continue S = 0 path_edges = set() for i in range(len(path)-1): u = path[i] v = path[i+1] if (u, v) in edges: path_edges.add((u, v)) path_edges.add((v, u)) S += edges[(u, v)] min_m = float('inf') for u in path: for v, w in adj[u]: if (u, v) not in path_edges: if w < min_m: min_m = w if min_m == float('inf'): print(-1) else: print(S + 2 * min_m) if __name__ == '__main__': main()