Approach
Depth-first search
For ABC348 E — Minimize Sum of Distances, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 73 lines of Python from the credited upstream file abc348_e.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 main():5 import sys6 7 sys.setrecursionlimit(5 * 10**6)8 9 input = sys.stdin.readline10 11 n = int(input())12 graph = [[] for _ in range(n)]13 14 for _ in range(n - 1):15 ai, bi = map(int, input().split())16 ai -= 117 bi -= 118 19 graph[ai].append(bi)20 graph[bi].append(ai)21 22 c = list(map(int, input().split()))23 c_total = sum(c)24 center = -125 26 27 28 def dfs(cur, parent=-1) -> int:29 nonlocal center30 31 c_summed = c[cur]32 c_max = 033 34 for to in graph[cur]:35 if to == parent:36 continue37 38 now = dfs(to, cur)39 c_max = max(c_max, now)40 c_summed += now41 42 43 c_max = max(c_max, c_total - c_summed)44 45 46 if c_max * 2 <= c_total:47 center = cur48 49 return c_summed50 51 dfs(0)52 53 54 ans = 055 56 def f(cur, parent=-1, dist=0):57 nonlocal ans58 59 ans += c[cur] * dist60 61 for to in graph[cur]:62 if to == parent:63 continue64 65 f(to, cur, dist + 1)66 67 f(center)68 print(ans)69 70 71if __name__ == "__main__":72 main()73