- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 51 lines of Python from the credited upstream file 882.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
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 reachableNodes(3 self,4 edges: list[list[int]],5 maxMoves: int,6 n: int,7 ) -> int:8 graph = [[] for _ in range(n)]9 dist = [maxMoves + 1] * n10 11 for u, v, cnt in edges:12 graph[u].append((v, cnt))13 graph[v].append((u, cnt))14 15 reachableNodes = self._dijkstra(graph, 0, maxMoves, dist)16 reachableSubnodes = 017 18 for u, v, cnt in edges:19 20 a = 0 if dist[u] > maxMoves else min(maxMoves - dist[u], cnt)21 22 b = 0 if dist[v] > maxMoves else min(maxMoves - dist[v], cnt)23 reachableSubnodes += min(a + b, cnt)24 25 return reachableNodes + reachableSubnodes26 27 def _dijkstra(28 self,29 graph: list[list[tuple[int, int]]],30 src: int,31 maxMoves: int,32 dist: list[int],33 ) -> int:34 dist[src] = 035 minHeap = [(dist[src], src)] 36 37 while minHeap:38 d, u = heapq.heappop(minHeap)39 40 if dist[u] >= maxMoves:41 break42 if d > dist[u]:43 continue44 for v, w in graph[u]:45 newDist = d + w + 146 if newDist < dist[v]:47 dist[v] = newDist48 heapq.heappush(minHeap, (newDist, v))49 50 return sum(d <= maxMoves for d in dist)51