Approach
Depth-first search
For Minimize the Total Price of the Trips, 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
- 44 lines of Python from the credited upstream file 2646.py.
- The implementation visibly relies on sequence storage.
- 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.
1class Solution:2 def minimumTotalPrice(self, n: int, edges: list[list[int]], price: list[int],3 trips: list[list[int]]) -> int:4 graph = [[] for _ in range(n)]5 6 for u, v in edges:7 graph[u].append(v)8 graph[v].append(u)9 10 11 count = [0] * n12 13 def dfsCount(u: int, prev: int, end: int, path: list[int]) -> None:14 path.append(u)15 if u == end:16 for i in path:17 count[i] += 118 return19 for v in graph[u]:20 if v != prev:21 dfsCount(v, u, end, path)22 path.pop()23 24 for start, end in trips:25 dfsCount(start, -1, end, [])26 27 @functools.lru_cache(None)28 def dfs(u: int, prev: int, parentHalved: bool) -> int:29 """30 Returns the minimum price sum for the i-th node, where its parent is31 halved parent or not halved not.32 """33 sumWithFullNode = price[u] * count[u] + sum(dfs(v, u, False)34 for v in graph[u]35 if v != prev)36 if parentHalved: 37 return sumWithFullNode38 sumWithHalvedNode = (price[u] 2) * count[u] + sum(dfs(v, u, True)39 for v in graph[u]40 if v != prev)41 return min(sumWithFullNode, sumWithHalvedNode)42 43 return dfs(0, -1, False)44