Approach
Breadth-first search
For ABC209 D — Collision, 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
- 67 lines of Python from the credited upstream file abc209_d.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 3class TreeDistance:4 def __init__(self, vertex_count, graph) -> None:5 self.dist = [0 for _ in range(vertex_count)]6 self._graph = graph7 self._visited = [False for _ in range(vertex_count)]8 9 def calc(self, start_vertex=0):10 self._bfs(start_vertex)11 12 return self.dist13 14 def _bfs(self, vertex):15 from collections import deque16 17 d = deque()18 d.append(vertex)19 self._visited[vertex] = True20 21 while d:22 di = d.popleft()23 24 for to in self._graph[di]:25 if self._visited[to]:26 continue27 28 self._visited[to] = True29 self.dist[to] = self.dist[di] + 130 d.append(to)31 32 33def main():34 from collections import deque35 import sys36 37 input = sys.stdin.readline38 39 n, q = map(int, input().split())40 graph = [[] for _ in range(n)]41 42 for _ in range(n - 1):43 ai, bi = map(int, input().split())44 ai -= 145 bi -= 146 47 graph[ai].append(bi)48 graph[bi].append(ai)49 50 td = TreeDistance(n, graph)51 dist = td.calc(0)52 53 for i in range(q):54 ci, di = map(int, input().split())55 ci -= 156 di -= 157 58 if abs(dist[ci] - dist[di]) % 2 == 1:59 print("Road")60 else:61 print("Town")62 63 64 65if __name__ == "__main__":66 main()67