Given N ropes, each rope has a length associated with it. At a time, only two consecutive small ropes tied at end form a large rope and cost of forming sum of their length. Find the minimum cost when all ropes are tied to form a single rope.
Examples:
Input: arr[] = {7, 6, 8, 6, 1, 1}
Output: 68
{7, 6, 8, 6, 1, 1} – {7, 6, 8, 6, 2}, cost = 2
{7, 6, 8, 6, 2} – {7, 6, 8, 8}, cost = 8
{7, 6, 8, 8} – {13, 8, 8}, cost = 13
{13, 8, 8} – {13, 16}, cost = 16
{13, 16} – {29}, cost = 29
2 + 8 + 13 + 16 + 29 = 68Input: arr[] = {10, 20, 30, 40}
Output: 190
Approach: A similar problem has been discussed in this article where any two ropes can be connected but in this problem, only the consecutive ropes can be connected. This problem can be solved by matrix chain multiplication technique of dynamic programming.
Optimal Substructure: In the 2nd example, the ropes can be connected as (((10 + 20) + 30) + 40)
Connect 10 and 20; cost = 30; expression becomes ((30 + 30) + 40)
Connect 30 and 30; cost = 90; expression becomes (60 + 40)
Connect 60 and 40; cost = 190 and we get a single rope
A simple solution is to place parenthesis at all possible places then calculate the cost for each segment and sum up to total cost. This can be done for all the valid parenthesis sequence and the minimum will be the answer.
Given ropes of length r1, r2, r3 and r4.
The connection can be formed in the following ways:
(((r1 + r2) + r3) + r4) or
((r1 + (r2 + r3)) + r4) or
((r1 + r2) + (r3 + r4)) …
Total cost of the 1st way is = r4 + 2 * r3 + 3 * (r2 + r1)
So when the set of parenthesis are placed, the problem is divided into subproblems of smaller sizes. Therefore, the problem has optimal substructure property and can be easily solved using recursion.
Overlapping Subproblems
(((r1 + r2) + r3) + r4)
and
((r1 + r2) + (r3 + r4))
both has a common part i.e. (r1 + r2)
So the solution is as follows:
- Precompute sum of different interval to save computation time.
- If we want two segments of {arr[i] arr[i+1] …arr[k]} and {arr[k+1] arr[k+2] …arr[j]} to connect, then our cost will be
MinCost(i, k) + MinCost(k + 1, j) + sum(arr[i] to arr[j])
where MinCost(i, k) = minimum cost in range(i, k) and sum(arr[i] to arr[j]) = cost to connect the rope segment of (i, k) and (k + 1, j). We can store the subproblems in dp table to save computation time.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the minimum cost // to connect the given ropes int MinCost(int arr[], int n) { // dp[i][j] = minimum cost in range (i, j) // sum[i][j] = sum of range (i, j) int dp[n + 5][n + 5], sum[n + 5][n + 5]; // Initializing the sum table memset(sum, 0, sizeof(0)); for (int i = 0; i < n; i++) { int k = arr[i]; for (int j = i; j < n; j++) { if (i == j) sum[i][j] = k; else { k += arr[j]; sum[i][j] = k; } } } // Computing minimum cost for all // the possible interval (i, j) // Left range for (int i = n - 1; i >= 0; i--) { // Right range for (int j = i; j < n; j++) { dp[i][j] = INT_MAX; // No cost for a single rope if (i == j) dp[i][j] = 0; else { for (int k = i; k < j; k++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum[i][j]); } } } } return dp[0][n - 1]; } // Driver code int main() { int arr[] = { 7, 6, 8, 6, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << MinCost(arr, n); return 0; } |
Java
// Java implementation of the approach class GFG { // Function to return the minimum cost // to connect the given ropes static int MinCost(int arr[], int n) { // dp[i][j] = minimum cost in range (i, j) // sum[i][j] = sum of range (i, j) int [][]dp = new int[n + 5][n + 5]; int [][]sum = new int[n + 5][n + 5]; // Initializing the sum table //memset(sum, 0, sizeof(0)); for (int i = 0; i < n; i++) { int k = arr[i]; for (int j = i; j < n; j++) { if (i == j) sum[i][j] = k; else { k += arr[j]; sum[i][j] = k; } } } // Computing minimum cost for all // the possible interval (i, j) // Left range for (int i = n - 1; i >= 0; i--) { // Right range for (int j = i; j < n; j++) { dp[i][j] = Integer.MAX_VALUE; // No cost for a single rope if (i == j) dp[i][j] = 0; else { for (int k = i; k < j; k++) { dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum[i][j]); } } } } return dp[0][n - 1]; } // Driver code public static void main(String []args) { int arr[] = { 7, 6, 8, 6, 1, 1 }; int n = arr.length; System.out.println(MinCost(arr, n)); } } // This code is contributed by 29AjayKumar |
Python3
# Python3 implementation of the approach # Function to return the minimum cost # to connect the given ropes def MinCost(arr, n): # dp[i][j] = minimum cost in range (i, j) # sum[i][j] = sum of range (i, j) dp = [[0 for i in range(n + 5)] for i in range(n + 5)] sum = [[0 for i in range(n + 5)] for i in range(n + 5)] for i in range(n): k = arr[i] for j in range(i, n): if (i == j): sum[i][j] = k else: k += arr[j] sum[i][j] = k # Computing minimum cost for all # the possible interval (i, j) # Left range for i in range(n - 1, -1, -1): # Right range for j in range(i, n): dp[i][j] = 10**9 # No cost for a single rope if (i == j): dp[i][j] = 0 else : for k in range(i, j): dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum[i][j]) return dp[0][n - 1] # Driver code arr = [7, 6, 8, 6, 1, 1] n = len(arr) print(MinCost(arr, n)) # This code is contributed # by Mohit Kumar |
C#
// C# implementation of the approach using System; class GFG { // Function to return the minimum cost // to connect the given ropes static int MinCost(int []arr, int n) { // dp[i,j] = minimum cost in range (i, j) // sum[i,j] = sum of range (i, j) int [,]dp = new int[n + 5, n + 5]; int [,]sum = new int[n + 5, n + 5]; // Initializing the sum table //memset(sum, 0, sizeof(0)); for (int i = 0; i < n; i++) { int k = arr[i]; for (int j = i; j < n; j++) { if (i == j) sum[i, j] = k; else { k += arr[j]; sum[i, j] = k; } } } // Computing minimum cost for all // the possible interval (i, j) // Left range for (int i = n - 1; i >= 0; i--) { // Right range for (int j = i; j < n; j++) { dp[i, j] = int.MaxValue; // No cost for a single rope if (i == j) dp[i, j] = 0; else { for (int k = i; k < j; k++) { dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k + 1, j] + sum[i, j]); } } } } return dp[0, n - 1]; } // Driver code public static void Main(String []args) { int []arr = { 7, 6, 8, 6, 1, 1 }; int n = arr.Length; Console.WriteLine(MinCost(arr, n)); } } // This code is contributed by Rajput-Ji |
68
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Ropes left after every removal of smallest
- Count possible binary strings of length N without P consecutive 0s and Q consecutive 1s
- Nuts & Bolts Problem (Lock & Key problem) | Set 1
- Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap)
- Check if array elements are consecutive | Added Method 3
- Find length of the longest consecutive path from a given starting character
- Find zeroes to be flipped so that number of consecutive 1's is maximized
- Minimum time to finish tasks without skipping two consecutive
- Find minimum sum such that one of every three consecutive elements is taken
- Maximum subsequence sum such that no three are consecutive
- Count minimum number of subsets (or subsequences) with consecutive numbers
- Minimum sum subsequence such that at least one of every four consecutive elements is picked
- Rearrange an array to minimize sum of product of consecutive pair elements
- Maximum consecutive one’s (or zeros) in a binary array
- Lexicographically smallest array after at-most K consecutive swaps
- Maximize sum of consecutive differences in a circular array
- Remove minimum elements from array such that no three consecutive element are either increasing or decreasing
- Delete consecutive same words in a sequence
- Pyramid form (increasing then decreasing) consecutive array using reduce operations
- Maximise the size of consecutive element subsets in an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

