- 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
- 55 lines of Python from the credited upstream file minimum-time-to-transport-all-individuals.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 minTime(self, n, k, m, time, mul):10 """11 :type n: int12 :type k: int13 :type m: int14 :type time: List[int]15 :type mul: List[float]16 :rtype: float17 """18 def update(d, r, s, mask, submask):19 t = lookup[submask]*mul[s]20 nr = r^121 ns = (s+int(t))%m22 new_mask = mask^submask23 nd = d+t24 if dist[nr][ns][new_mask] > nd:25 dist[nr][ns][new_mask] = nd26 heapq.heappush(min_heap, (nd, nr, ns, new_mask))27 28 popcount = [0]*(1<<n) 29 for i in xrange(1, (1<<n)):30 popcount[i] = popcount[i>>1]+(i&1)31 lookup = [max(time[i] for i in xrange(n) if mask&(1<<i)) if mask else 0 for mask in xrange(1<<n)] 32 INF = float("inf")33 dist = [[[INF]*(1<<n) for _ in xrange(m)] for _ in xrange(2)]34 dist[0][0][(1<<n)-1] = 0.035 min_heap = [(0.0, 0, 0, (1<<n)-1)]36 while min_heap:37 d, r, s, mask = heapq.heappop(min_heap) 38 if d != dist[r][s][mask]:39 continue40 if mask == 0:41 assert(r == 1)42 return d43 if r == 0:44 submask = mask45 while submask: 46 if popcount[submask] <= k:47 update(d, r, s, mask, submask)48 submask = (submask-1)&mask49 else:50 for i in xrange(n): 51 if mask&(1<<i):52 continue53 update(d, r, s, mask, 1<<i)54 return -1.055