|
| 1 | +import sys |
| 2 | +from collections import defaultdict, deque |
| 3 | +from typing import cast |
| 4 | + |
| 5 | +read = lambda: sys.stdin.readline().rstrip() |
| 6 | + |
| 7 | + |
| 8 | +class Problem: |
| 9 | + def __init__(self): |
| 10 | + self.n = int(read()) |
| 11 | + |
| 12 | + self.nodes = defaultdict(set[tuple[int, int]]) |
| 13 | + for _ in range(self.n - 1): |
| 14 | + src, dest, distance = map(int, read().split()) |
| 15 | + self.nodes[src].add((dest, distance)) |
| 16 | + self.nodes[dest].add((src, distance)) |
| 17 | + |
| 18 | + self.queries = [cast(tuple[int, int], tuple(map(int, read().split()))) for _ in range(int(read()))] |
| 19 | + |
| 20 | + self.depth, self.parent, self.weights = self.make_tree() |
| 21 | + |
| 22 | + def solve(self) -> None: |
| 23 | + for x, y in self.queries: |
| 24 | + print(self.weights[x] + self.weights[y] - 2 * self.weights[self.lca(x, y)]) |
| 25 | + |
| 26 | + def make_tree(self) -> tuple[list[int], list[list[int]], list[int]]: |
| 27 | + queue, visited = deque([(1, 0)]), {1} |
| 28 | + depth, parent, weights = ( |
| 29 | + [0 for _ in range(self.n + 1)], |
| 30 | + [[0 for _ in range(20)] for _ in range(self.n + 1)], |
| 31 | + [0 for _ in range(self.n + 1)], |
| 32 | + ) |
| 33 | + |
| 34 | + while queue: |
| 35 | + node, idx = queue.popleft() |
| 36 | + depth[node] = idx |
| 37 | + |
| 38 | + for child, distance in self.nodes[node]: |
| 39 | + if child not in visited: |
| 40 | + queue.append((child, idx + 1)) |
| 41 | + visited.add(child) |
| 42 | + parent[child][0] = node |
| 43 | + weights[child] = weights[node] + distance |
| 44 | + |
| 45 | + for k in range(1, 20): |
| 46 | + for node in range(1, self.n + 1): |
| 47 | + parent[node][k] = parent[parent[node][k - 1]][k - 1] |
| 48 | + |
| 49 | + return depth, parent, weights |
| 50 | + |
| 51 | + def lca(self, x: int, y: int) -> int: |
| 52 | + if self.depth[x] < self.depth[y]: |
| 53 | + x, y = y, x |
| 54 | + |
| 55 | + for k in range(20)[::-1]: |
| 56 | + if self.depth[x] - (1 << k) >= self.depth[y]: |
| 57 | + x = self.parent[x][k] |
| 58 | + |
| 59 | + if x == y: |
| 60 | + return x |
| 61 | + |
| 62 | + for k in range(20)[::-1]: |
| 63 | + if self.parent[x][k] != self.parent[y][k]: |
| 64 | + x, y = self.parent[x][k], self.parent[y][k] |
| 65 | + |
| 66 | + return self.parent[x][0] |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + Problem().solve() |
0 commit comments