Approach
Depth-first search
For Number of Ways to Assign Edge Weights II, 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
- 60 lines of Python from the credited upstream file 3559.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 assignEdgeWeights(3 self,4 edges: list[list[int]],5 queries: list[list[int]]6 ) -> list[int]:7 MOD = 1_000_000_0078 LOG = 17 9 n = len(edges) + 110 ans = []11 depth = [0] * (n + 1)12 graph = [[] for _ in range(n + 1)]13 parent = [[-1] * (n + 1) for _ in range(LOG)]14 15 for u, v in edges:16 graph[u].append(v)17 graph[v].append(u)18 19 def dfs(u: int, p: int) -> None:20 parent[0][u] = p21 for v in graph[u]:22 if v != p:23 depth[v] = depth[u] + 124 dfs(v, u)25 26 dfs(1, -1)27 28 for k in range(1, LOG):29 for v in range(1, n + 1):30 if parent[k - 1][v] != -1:31 parent[k][v] = parent[k - 1][parent[k - 1][v]]32 33 def lca(u: int, v: int) -> int:34 if depth[u] < depth[v]:35 u, v = v, u36 37 for k in reversed(range(LOG)):38 if parent[k][u] != -1 and depth[parent[k][u]] >= depth[v]:39 u = parent[k][u]40 41 if u == v:42 return u43 44 for k in reversed(range(LOG)):45 if parent[k][u] != -1 and parent[k][u] != parent[k][v]:46 u = parent[k][u]47 v = parent[k][v]48 49 return parent[0][u]50 51 for u, v in queries:52 if u == v:53 ans.append(0)54 else:55 a = lca(u, v)56 d = depth[u] + depth[v] - 2 * depth[a]57 ans.append(pow(2, d - 1, MOD))58 59 return ans60