Approach
Breadth-first search
For ABC148 F — Playing Tag on Tree, 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
- 70 lines of Python from the credited upstream file abc148_f.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 TreeDistance:5 def __init__(self, vertex_count, graph) -> None:6 self.dist = [0 for _ in range(vertex_count)]7 self._graph = graph8 self._visited = [False for _ in range(vertex_count)]9 10 def calc(self, start_vertex):11 self._bfs(start_vertex)12 13 return self.dist14 15 def _bfs(self, vertex):16 from collections import deque17 18 d = deque()19 d.append(vertex)20 self._visited[vertex] = True21 22 while d:23 di = d.popleft()24 25 for to in self._graph[di]:26 if self._visited[to]:27 continue28 29 self._visited[to] = True30 self.dist[to] = self.dist[di] + 131 d.append(to)32 33 34def main():35 import sys36 37 input = sys.stdin.readline38 39 n, u, v = map(int, input().split())40 u -= 141 v -= 142 43 graph = [[] for _ in range(n)]44 45 for _ in range(n - 1):46 ai, bi = map(int, input().split())47 ai -= 148 bi -= 149 50 graph[ai].append(bi)51 graph[bi].append(ai)52 53 dist1 = TreeDistance(n, graph)54 takahashi_dist = dist1.calc(u)55 dist2 = TreeDistance(n, graph)56 aoki_dist = dist2.calc(v)57 58 dist_max = 059 60 for t_dist, a_dist in zip(takahashi_dist, aoki_dist):61 if t_dist < a_dist:62 dist_max = max(dist_max, a_dist)63 64 ans = dist_max - 165 print(ans)66 67 68if __name__ == "__main__":69 main()70