- 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
- 86 lines of Python from the credited upstream file minimum-cost-to-buy-apples-ii.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.
123 4import heapq5 6 78class Solution(object):9 def minCost(self, n, prices, roads):10 """11 :type n: int12 :type prices: List[int]13 :type roads: List[List[int]]14 :rtype: List[int]15 """16 INF = float("inf")17 def dijkstra(start, target):18 best = [INF]*len(adj)19 best[start] = 020 min_heap = [(best[start], start)]21 while min_heap:22 curr, u = heapq.heappop(min_heap)23 if curr != best[u]:24 continue25 if u == target:26 return curr27 for v, w in adj[u]: 28 if best[v] <= curr+w:29 continue30 best[v] = curr+w31 heapq.heappush(min_heap, (best[v], v))32 return INF33 34 adj = [[] for _ in xrange(2*n)]35 for u, v, c, t in roads:36 adj[u].append((v, c))37 adj[v].append((u, c))38 adj[u+n].append((v+n, c*t))39 adj[v+n].append((u+n, c*t))40 for i in xrange(n):41 adj[i].append((i+n , prices[i]))42 return [dijkstra(i, i+n) for i in xrange(n)]43 44 454647import heapq48 49 5051class Solution2(object):52 def minCost(self, n, prices, roads):53 """54 :type n: int55 :type prices: List[int]56 :type roads: List[List[int]]57 :rtype: List[int]58 """59 INF = float("inf")60 def dijkstra(adj, start):61 best = [INF]*len(adj)62 best[start] = 063 min_heap = [(best[start], start)]64 while min_heap:65 curr, u = heapq.heappop(min_heap)66 if curr != best[u]:67 continue68 for v, w in adj[u]: 69 if best[v] <= curr+w:70 continue71 best[v] = curr+w72 heapq.heappush(min_heap, (best[v], v))73 return best74 75 adj = [[[] for _ in xrange(n)] for _ in xrange(2)]76 for u, v, c, t in roads:77 adj[0][u].append((v, c))78 adj[0][v].append((u, c))79 adj[1][u].append((v, c*t))80 adj[1][v].append((u, c*t))81 result = [0]*n82 for i in xrange(n):83 dist = [dijkstra(adj[j], i) for j in xrange(2)]84 result[i] = min(dist[0][j]+prices[j]+dist[1][j] for j in xrange(n))85 return result86