[LeetCode] Minimum Cost to Merge Sorted Lists

3801. Minimum Cost to Merge Sorted Lists

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
long long meds[1<<13], szs[1<<13], dp[1<<13];
class Solution {
bool bit(int a, int b) {
return (a>>b) & 1;
}
void med(vector<vector<int>>& A, int g) {
long long& sz = szs[g] = 0;
long long& med = meds[g] = LLONG_MAX;
for(int i = 0; i < A.size(); i++) {
if(!bit(g,i)) continue;
sz += A[i].size();
}
int t = (sz - 1) / 2, l = -1e9, r = 1e9;
while(l <= r) {
int m = l + (r - l) / 2, sum = 0;
for(int i = 0; i < A.size(); i++) {
if(!bit(g,i)) continue;
sum += upper_bound(begin(A[i]), end(A[i]), m) - begin(A[i]);
}
if(sum > t) {
r = m - 1;
med = m;
} else l = m + 1;
}
}
long long helper(int mask) {
if(dp[mask] != -1) return dp[mask];
long long& res = dp[mask] = LLONG_MAX;
for(int sub = (mask - 1) & mask; sub; sub = (sub - 1) & mask) {
int g1 = mask ^ sub, g2 = sub;
if(g2 < g1) break;
res = min(res, helper(g1) + helper(g2) + szs[mask] + abs(meds[g1] - meds[g2]));
}
return res;
}
public:
long long minMergeCost(vector<vector<int>>& lists) {
int n = lists.size();
for(int i = 1; i < 1<<n; i++) med(lists,i);
memset(dp,-1,sizeof dp);
for(int i = 0; i < n; i++) dp[1<<i] = 0;
dp[0] = 0;
return helper((1<<n) - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-cost-to-merge-sorted-lists/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.