Approach
Breadth-first search
For ABC220 F — Distance Sums 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 abc220_f.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected, together with recursive traversal.
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 4def calc_depth(vertex_count: int, graph):5 from collections import deque6 7 PENDING = -18 depth = [PENDING for _ in range(vertex_count)]9 parent = [PENDING for _ in range(vertex_count)]10 depth[0], parent[0] = 0, 011 d = deque()12 d.append(0)13 14 while d:15 vertex = d.popleft()16 17 for g in graph[vertex]:18 if depth[g] == PENDING:19 depth[g] = depth[vertex] + 120 parent[g] = vertex21 d.append(g)22 23 return depth24 25 26def main():27 import sys28 29 input = sys.stdin.readline30 sys.setrecursionlimit(10 ** 7)31 32 n = int(input())33 graph = [[] for _ in range(n)]34 35 for _ in range(n - 1):36 ai, bi = map(int, input().split())37 ai -= 138 bi -= 139 40 graph[ai].append(bi)41 graph[bi].append(ai)42 43 44 depth = calc_depth(n, graph)45 tree_size = [0] * n46 ans = [0] * n47 ans[0] = sum(depth)48 49 50 def dfs(vertex, parent=-1):51 tree_size[vertex] = 152 53 for to in graph[vertex]:54 if to == parent:55 continue56 57 tree_size[vertex] += dfs(to, vertex)58 59 return tree_size[vertex]60 61 dfs(0)62 63 64 def dfs2(vertex, parent=-1):65 for to in graph[vertex]:66 if to == parent:67 continue68 69 ans[to] = ans[vertex] - tree_size[to] + (n - tree_size[to])70 dfs2(to, vertex)71 72 dfs2(0)73 print(*ans, sep='\n')74 75 76if __name__ == "__main__":77 main()78