Suppose we are given an array arr that contains n positive integer numbers. We are also given an integer number j. The task we have to perform is to merge j numbers into a single number by adding them. The cost of merging is equal to the addition of the j numbers we have selected. We have to find out the minimum possible cost for this merging operation.
So, if the input is like arr = [2, 5, 6, 2, 3, 1, 3], j = 4, then the output will be 31.
Cost to merge 2, 3, 1, 3 is equal to 2 + 3 + 1 + 3 = 9.
The array after the merge operation becomes [2, 5, 6, 9]. The cost of the second merge operation is equal to 2 + 5 + 6 + 9 = 22. So, the total cost of the merge operation becomes 22 + 9 = 31. This is the minimum merging cost.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include<bits/stdc++.h> using namespace std; int solve(vector<int>& arr, int j) { int n = arr.size(); if ((n - 1) % (j - 1) != 0) return -1; vector<int> temp(n + 1); for (int i = n - 1; i >= 0; i--) { temp[i] = arr[i] + temp[i + 1]; } vector<vector<int>> dynArr(n, vector<int>(n)); for (int k = j; k <= n; k++) { for (int le = 0, rg = k - 1; rg < n; le++, rg++) { dynArr[le][rg] = INT_MAX; for (int i = le; i < rg; i += j - 1) { dynArr[le][rg] = min(dynArr[le][rg], dynArr[le][i] + dynArr[i + 1][rg]); } if ((rg - le) % (j - 1) == 0) { dynArr[le][rg] += temp[le] - temp[rg + 1]; } } } return dynArr[0][n - 1]; } int main() { vector<int> arr = {2, 5, 6, 2, 3, 1, 3}; cout<< solve(arr, 4) <<endl; return 0; }
{2, 5, 6, 2, 3, 1, 3}, 4
31