Approach
Depth-first search
For Minimum Score After Removals on a Tree, 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
- 43 lines of Python from the credited upstream file 2322.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 minimumScore(self, nums: list[int], edges: list[list[int]]) -> int:3 n = len(nums)4 xors = functools.reduce(operator.xor, nums)5 subXors = nums[:]6 tree = [[] for _ in range(n)]7 children = [{i} for i in range(n)]8 9 for u, v in edges:10 tree[u].append(v)11 tree[v].append(u)12 13 def dfs(u: int, prev: int) -> tuple[int, set[int]]:14 for v in tree[u]:15 if v == prev:16 continue17 vXor, vChildren = dfs(v, u)18 subXors[u] ^= vXor19 children[u] |= vChildren20 return subXors[u], children[u]21 22 dfs(0, -1)23 24 ans = math.inf25 for i in range(len(edges)):26 a, b = edges[i]27 if b in children[a]:28 a, b = b, a29 for j in range(i):30 c, d = edges[j]31 if d in children[c]:32 c, d = d, c33 34 if c in children[a] and a != c:35 cands = [subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]]36 elif a in children[c] and a != c:37 cands = [subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]]38 else:39 cands = [subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]]40 ans = min(ans, max(cands) - min(cands))41 42 return ans43