- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 59 lines of Python from the credited upstream file minimum-cost-to-merge-sorted-lists.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import heapq5import bisect6 7 89class Solution(object):10 def minMergeCost(self, lists):11 """12 :type lists: List[List[int]]13 :rtype: int14 """15 INF = float("inf")16 def merge(lists):17 result = []18 min_heap = [(lists[i][0], i, 0) for i in xrange(len(lists))]19 heapq.heapify(min_heap)20 while min_heap:21 x, i, j = heapq.heappop(min_heap)22 result.append(x)23 if j+1 < len(lists[i]):24 heapq.heappush(min_heap, (lists[i][j+1], i, j+1))25 return result26 27 def binary_search(left, right, check):28 while left <= right:29 mid = left+(right-left)230 if check(mid):31 right = mid-132 else:33 left = mid+134 return left35 36 def check(x):37 return sum(bisect.bisect_right(lists[i], sorted_vals[x]) for i in range(len(lists)) if mask&(1<<i)) >= (dp1[mask]+1)238 39 dp1 = [0]*(1<<len(lists))40 for i in xrange(len(lists)): 41 dp1[1<<i] = len(lists[i])42 for mask in xrange(1, len(dp1)): 43 dp1[mask] = dp1[mask^(mask&-mask)]+dp1[mask&-mask]44 sorted_vals = merge(lists) 45 sorted_vals = [sorted_vals[i] for i in xrange(len(sorted_vals)) if i+1 == len(sorted_vals) or sorted_vals[i+1] != sorted_vals[i]]46 dp2 = [0]*(1<<len(lists))47 for mask in xrange(1, len(dp2)): 48 dp2[mask] = sorted_vals[binary_search(0, len(sorted_vals)-1, check)]49 dp3 = [0]*(1<<len(lists))50 for mask in xrange(1, len(dp3)): 51 if mask&(mask-1) == 0:52 continue53 dp3[mask] = INF54 submask = (mask-1)&mask55 while submask > mask^submask:56 dp3[mask] = min(dp3[mask], dp3[submask]+dp3[mask^submask]+abs(dp2[submask]-dp2[mask^submask])+dp1[mask])57 submask = (submask-1)&mask58 return dp3[-1]59