Minimum Cost to Merge Sorted Lists Problem
Description
LeetCode Problem 3801.
You are given a 2D integer array lists, where each lists[i] is a non-empty array of integers sorted in non-decreasing order.
You may repeatedly choose two lists a = lists[i] and b = lists[j], where i != j, and merge them. The cost to merge a and b is:
len(a) + len(b) + abs(median(a) - median(b)), where len and median denote the list length and median, respectively.
After merging a and b, remove both a and b from lists and insert the new merged sorted list in any position. Repeat merges until only one list remains.
Return an integer denoting the minimum total cost required to merge all lists into one single sorted list.
The median of an array is the middle element after sorting it in non-decreasing order. If the array has an even number of elements, the median is the left middle element.
Example 1:
Input: lists = [[1,3,5],[2,4],[6,7,8]]
Output: 18
Explanation:
Merge a = [1, 3, 5] and b = [2, 4]:
- len(a) = 3 and len(b) = 2
- median(a) = 3 and median(b) = 2
- cost = len(a) + len(b) + abs(median(a) - median(b)) = 3 + 2 + abs(3 - 2) = 6
So lists becomes [[1, 2, 3, 4, 5], [6, 7, 8]].
Merge a = [1, 2, 3, 4, 5] and b = [6, 7, 8]:
- len(a) = 5 and len(b) = 3
- median(a) = 3 and median(b) = 7
- cost = len(a) + len(b) + abs(median(a) - median(b)) = 5 + 3 + abs(3 - 7) = 12
So lists becomes [[1, 2, 3, 4, 5, 6, 7, 8]], and total cost is 6 + 12 = 18.
Example 2:
Input: lists = [[1,1,5],[1,4,7,8]]
Output: 10
Explanation:
Merge a = [1, 1, 5] and b = [1, 4, 7, 8]:
- len(a) = 3 and len(b) = 4
- median(a) = 1 and median(b) = 4
- cost = len(a) + len(b) + abs(median(a) - median(b)) = 3 + 4 + abs(1 - 4) = 10
So lists becomes [[1, 1, 1, 4, 5, 7, 8]], and total cost is 10.
Example 3:
Input: lists = [[1],[3]]
Output: 4
Explanation:
Merge a = [1] and b = [3]:
- len(a) = 1 and len(b) = 1
- median(a) = 1 and median(b) = 3
- cost = len(a) + len(b) + abs(median(a) - median(b)) = 1 + 1 + abs(1 - 3) = 4
So lists becomes [[1, 3]], and total cost is 4.
Example 4:
Input: lists = [[1],[1]]
Output: 2
Explanation:
The total cost is len(a) + len(b) + abs(median(a) - median(b)) = 1 + 1 + abs(1 - 1) = 2.
Constraints:
2 <= lists.length <= 121 <= lists[i].length <= 500-10^9 <= lists[i][j] <= 10^9lists[i]is sorted in non-decreasing order.- The sum of
lists[i].lengthwill not exceed 2000.
Solution
Approach: State Compression DP
There are at most 12 lists, so a bitmask can stand for any subset of them.
The merged result of a set of lists is the sorted union of their elements, so its length and median depend only on the set, not on the merge order. The median is the left middle element, that is the (len + 1) / 2-th smallest value.
For every nonempty subset i, precompute:
cnt[i]: the number of elements in the subset;med[i]: the median, found by binary searching over the distinct values and counting how many elements of the subset are at mostmid.
Let f[i] be the minimum cost to merge the lists of subset i into one. A single list costs 0. Otherwise split i into two nonempty parts j and k = i ^ j that are merged last:
f[i] = min over j of (f[j] + f[k] + |med[j] - med[k]|) + cnt[i]
The length part of the last merge is always cnt[i]. The answer is f[2^n - 1].
Complexity: Time O(3^n + 2^n * n * log V * log L), space O(2^n), where n is the number of lists, V the number of distinct values and L the longest list.
from bisect import bisect_right
from math import inf
class Solution:
def minMergeCost(self, lists: List[List[int]]) -> int:
n = len(lists)
vals = sorted({x for v in lists for x in v})
cnt = [0] * (1 << n)
med = [0] * (1 << n)
for i in range(1, 1 << n):
for j, v in enumerate(lists):
if i >> j & 1:
cnt[i] += len(v)
need = (cnt[i] + 1) // 2
l, r = 0, len(vals) - 1
while l < r:
mid = (l + r) >> 1
le = 0
b = i
while b:
t = (b & -b).bit_length() - 1
le += bisect_right(lists[t], vals[mid])
if le >= need:
break
b &= b - 1
if le >= need:
r = mid
else:
l = mid + 1
med[i] = vals[l]
f = [inf] * (1 << n)
for i in range(1, 1 << n):
if i & (i - 1) == 0:
f[i] = 0
continue
j = (i - 1) & i
while j:
k = i ^ j
if j <= k:
f[i] = min(f[i], f[j] + f[k] + abs(med[j] - med[k]))
j = (j - 1) & i
f[i] += cnt[i]
return f[-1]