- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 85 lines of Python from the credited upstream file 2846.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 minOperationsQueries(3 self,4 n: int,5 edges: list[list[int]],6 queries: list[list[int]],7 ) -> list[int]:8 MAX = 269 m = math.ceil(math.log2(n))10 graph = [[] for _ in range(n)]11 12 jump = [[0] * m for _ in range(n)]13 14 depth = [0] * n15 16 count = [[] for _ in range(n)]17 18 for u, v, w in edges:19 graph[u].append((v, w))20 graph[v].append((u, w))21 22 count[0] = [0] * (MAX + 1)23 self._dfs(graph, 0, -1, jump, depth, count)24 25 for j in range(1, m):26 for i in range(n):27 jump[i][j] = jump[jump[i][j - 1]][j - 1]28 29 def getMinOperations(u: int, v: int) -> int:30 """31 Returns the minimum number of operations to make the edge weight32 equilibrium between (u, v).33 """34 lca = self._getLCA(u, v, jump, depth)35 36 numEdges = depth[u] + depth[v] - 2 * depth[lca]37 38 maxFreq = max(count[u][j] + count[v][j] - 2 * count[lca][j]39 for j in range(1, MAX + 1))40 return numEdges - maxFreq41 42 return [getMinOperations(u, v) for u, v in queries]43 44 def _dfs(45 self,46 graph: list[list[tuple[int, int]]],47 u: int,48 prev: int,49 jump: list[list[int]],50 depth: list[int],51 count: list[list[int]]52 ) -> None:53 for v, w in graph[u]:54 if v == prev:55 continue56 jump[v][0] = u57 depth[v] = depth[u] + 158 count[v] = count[u][:]59 count[v][w] += 160 self._dfs(graph, v, u, jump, depth, count)61 62 def _getLCA(63 self,64 u: int,65 v: int,66 jump: list[list[int]],67 depth: list[int]68 ) -> int:69 """Returns the lca(u, v) by binary jump."""70 71 if depth[u] > depth[v]:72 return self._getLCA(v, u, jump, depth)73 74 for j in range(len(jump[0])):75 if depth[v] - depth[u] >> j & 1:76 v = jump[v][j]77 if u == v:78 return u79 80 for j in range(len(jump[0]) - 1, -1, -1):81 if jump[u][j] != jump[v][j]:82 u = jump[u][j]83 v = jump[v][j]84 return jump[u][0]85