Approach
Breadth-first search
For ABC361 E — Tree and Hamilton Path 2, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 78 lines of Python from the credited upstream file abc361_e.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4class TreeDiameter:5 def __init__(self, vertex_count: int, graph) -> None:6 self.vertex_count = vertex_count7 self.graph = graph8 9 def calc(self, source: int) -> tuple[int, int, int]:10 assert 0 <= source < self.vertex_count11 12 p, _ = self._find_farthest_vertex(source=source)13 q, dist_max = self._find_farthest_vertex(source=p)14 15 return dist_max, p, q16 17 def _find_farthest_vertex(self, source: int) -> tuple[int, int]:18 from collections import deque19 20 visited = [False for _ in range(self.vertex_count)]21 que = deque([(0, source)])22 23 farthest_vertex = source24 dist_max = 025 26 while que:27 dist, vertex = que.popleft()28 29 if visited[vertex]:30 continue31 32 visited[vertex] = True33 34 for weight, next_vertex in self.graph[vertex]:35 if not (0 <= next_vertex < self.vertex_count):36 continue37 if visited[next_vertex]:38 continue39 40 new_dist = dist + weight41 que.append((new_dist, next_vertex))42 43 if new_dist > dist_max:44 farthest_vertex = next_vertex45 dist_max = new_dist46 47 return farthest_vertex, dist_max48 49 50def main():51 import sys52 53 input = sys.stdin.readline54 55 n = int(input())56 graph = [[] for _ in range(n)]57 ans = 058 59 60 for _ in range(n - 1):61 ai, bi, ci = map(int, input().split())62 ai -= 163 bi -= 164 65 graph[ai].append((ci, bi))66 graph[bi].append((ci, ai))67 68 ans += ci * 269 70 tree_diameter = TreeDiameter(vertex_count=n, graph=graph)71 dist, _, _ = tree_diameter.calc(source=0)72 ans -= dist73 print(ans)74 75 76if __name__ == "__main__":77 main()78