Open In App

N consecutive ropes problem

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 = 68

Input: 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


Javascript




<script>
 
// JavaScript implementation of the approach
 
 
// Function to return the minimum cost
// to connect the given ropes
function MinCost(arr, n) {
 
    // dp[i][j] = minimum cost in range (i, j)
    // sum[i][j] = sum of range (i, j)
    let dp = new Array(n + 5);
    let sum = new Array(n + 5);
 
    for (let i = 0; i < n + 5; i++) {
        dp[i] = [];
        sum[i] = [];
        for (let j = 0; j < n + 5; j++) {
            dp[i].push(0)
            sum[i].push(0)
        }
 
    }
     
console.log(dp)
    for (let i = 0; i < n; i++)
    {
        let k = arr[i];
        for (let 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 (let i = n - 1; i >= 0; i--)
    {
   
        // Right range
        for (let j = i; j < n; j++)
        {
            dp[i][j] = Number.MAX_SAFE_INTEGER;
   
            // No cost for a single rope
            if (i == j)
                dp[i][j] = 0;
            else
            {
                for (let 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
 
let arr = [7, 6, 8, 6, 1, 1];
let n = arr.length;
 
document.write(MinCost(arr, n));
 
// This code is contributed by _saurabh_jaiswal
 
</script>


Output: 

68

 

Time Complexity: O(n3)
Auxiliary Space: O(n2),  where n is the size of the given array.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads