Costo mínimo para fusionar todos los elementos de List

Dada una lista de N enteros, la tarea es fusionar todos los elementos de la lista en uno con el mínimo costo posible. La regla para la fusión es la siguiente: 
elija dos elementos adyacentes de la lista con valores, digamos X e Y , y combínelos en un solo elemento con valor (X + Y) pagando un costo total de (X + Y) .
Ejemplos: 
 

Entrada: arr[] = {1, 3, 7} 
Salida: 15 
Todas las formas posibles de fusionar: 
a) {1, 3, 7} (costo = 0) -> {4, 7} (costo = 0+4 = 4) -> 11 (costo = 4+11 = 15) 
b) {1, 3, 7} (costo = 0) -> {1, 10} (costo = 0+10= 10) -> 11 (costo = 10+11 = 21) 
Por lo tanto, ans = 15
Entrada: arr[] = {1, 2, 3, 4} 
Salida: 19 
 

Enfoque: Este problema se puede resolver mediante programación dinámica . Definamos primero los estados del DP. DP[l][r] será el costo mínimo de fusionar el subarreglo arr[l…r] en uno. 
Ahora, veamos la relación de recurrencia: 
 

DP[l][r] = min(S(l, l) + S(l + 1, r) + DP[l][l] + DP[l + 1][r], S(l, l + 1) + S(l + 2, r) + DP[l][l + 1] + DP[l + 2][r], …, S(l, r – 1) + S(r, r) + DP[l][r – 1] + DP[r][r]) = S(l, r) + min(DP[l][l] + DP[l + 1][r], DP[l] [l + 1] + DP[l + 2][r], …, DP[l][r – 1] + DP[r][r]) 
donde S(x, y) es la suma de todos los elementos del subarreglo arr[x…y] 
 

La complejidad temporal del enfoque será O(N 3 ) ya que hay N * N estados en total y cada estado requiere O(N) tiempo para resolverse en general.
A continuación se muestra la implementación del enfoque anterior: 
 

CPP


// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

#define N 401

// To store the states of DP
int dp[N][N];
bool v[N][N];

// Function to return the minimum merge cost
int minMergeCost(int i, int j, int* arr)
{

    // Base case
    if (i == j)
        return 0;

    // If the state has been solved before
    if (v[i][j])
        return dp[i][j];

    // Marking the state as solved
    v[i][j] = 1;
    int& x = dp[i][j];

    // Reference to dp[i][j]
    x = INT_MAX;

    // To store the sum of all the
    // elements in the subarray arr[i...j]
    int tot = 0;
    for (int k = i; k <= j; k++)
        tot += arr[k];

    // Loop to iterate the recurrence
    for (int k = i + 1; k <= j; k++) {
        x = min(x, tot + minMergeCost(i, k - 1, arr)
                       + minMergeCost(k, j, arr));
    }

    // Returning the solved value
    return x;
}

// Driver code
int main()
{
    int arr[] = { 1, 3, 7 };
    int n = sizeof(arr) / sizeof(int);

    cout << minMergeCost(0, n - 1, arr);

    return 0;
}

Java


// Java implementation of the approach
class GFG
{

static final int N = 401;

// To store the states of DP
static int [][]dp = new int[N][N];
static boolean [][]v = new boolean[N][N];

// Function to return the minimum merge cost
static int minMergeCost(int i, int j, int[] arr)
{

    // Base case
    if (i == j)
        return 0;

    // If the state has been solved before
    if (v[i][j])
        return dp[i][j];

    // Marking the state as solved
    v[i][j] = true;
    int x = dp[i][j];

    // Reference to dp[i][j]
    x = Integer.MAX_VALUE;

    // To store the sum of all the
    // elements in the subarray arr[i...j]
    int tot = 0;
    for (int k = i; k <= j; k++)
        tot += arr[k];

    // Loop to iterate the recurrence
    for (int k = i + 1; k <= j; k++) 
    {
        x = Math.min(x, tot + minMergeCost(i, k - 1, arr)
                    + minMergeCost(k, j, arr));
    }

    // Returning the solved value
    return x;
}

// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 3, 7 };
    int n = arr.length;

    System.out.print(minMergeCost(0, n - 1, arr));
}
}

// This code is contributed by PrinciRaj1992


Python3


# Python3 implementation of the approach
import sys

N = 401;

# To store the states of DP
dp = [[0 for i in range(N)] for j in range(N)];
v = [[False for i in range(N)] for j in range(N)];

# Function to return the minimum merge cost
def minMergeCost(i, j, arr):

    # Base case
    if (i == j):
        return 0;

    # If the state has been solved before
    if (v[i][j]):
        return dp[i][j];

    # Marking the state as solved
    v[i][j] = True;
    x = dp[i][j];

    # Reference to dp[i][j]
    x = sys.maxsize;

    # To store the sum of all the
    # elements in the subarray arr[i...j]
    tot = 0;
    for k in range(i, j + 1):
        tot += arr[k];

    # Loop to iterate the recurrence
    for k in range(i + 1, j + 1):
        x = min(x, tot + minMergeCost(i, k - 1, arr) + \
                minMergeCost(k, j, arr));
    
    # Returning the solved value
    return x;

# Driver code
if __name__ == '__main__':
    arr = [ 1, 3, 7 ];
    n = len(arr);

    print(minMergeCost(0, n - 1, arr));

# This code is contributed by PrinciRaj1992


C#


// C# implementation of the approach
using System;

class GFG
{

static readonly int N = 401;

// To store the states of DP
static int [,]dp = new int[N, N];
static bool [,]v = new bool[N, N];

// Function to return the minimum merge cost
static int minMergeCost(int i, int j, int[] arr)
{

    // Base case
    if (i == j)
        return 0;

    // If the state has been solved before
    if (v[i, j])
        return dp[i, j];

    // Marking the state as solved
    v[i, j] = true;
    int x = dp[i, j];

    // Reference to dp[i,j]
    x = int.MaxValue;

    // To store the sum of all the
    // elements in the subarray arr[i...j]
    int tot = 0;
    for (int k = i; k <= j; k++)
        tot += arr[k];

    // Loop to iterate the recurrence
    for (int k = i + 1; k <= j; k++) 
    {
        x = Math.Min(x, tot + minMergeCost(i, k - 1, arr)
                    + minMergeCost(k, j, arr));
    }

    // Returning the solved value
    return x;
}

// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 3, 7 };
    int n = arr.Length;

    Console.Write(minMergeCost(0, n - 1, arr));
}
}

// This code is contributed by 29AjayKumar


Javascript

<script>

// Javascript implementation of the approach

var N = 401

// To store the states of DP
var dp = Array.from(Array(N), ()=> Array(N));
var v = Array.from(Array(N), ()=> Array(N));

// Function to return the minimum merge cost
function minMergeCost(i, j, arr)
{

    // Base case
    if (i == j)
        return 0;

    // If the state has been solved before
    if (v[i][j])
        return dp[i][j];

    // Marking the state as solved
    v[i][j] = 1;
    var x = dp[i][j];

    // Reference to dp[i][j]
    x = 1000000000;

    // To store the sum of all the
    // elements in the subarray arr[i...j]
    var tot = 0;
    for (var k = i; k <= j; k++)
        tot += arr[k];

    // Loop to iterate the recurrence
    for (var k = i + 1; k <= j; k++) {
        x = Math.min(x, tot + minMergeCost(i, k - 1, arr)
                       + minMergeCost(k, j, arr));
    }

    // Returning the solved value
    return x;
}

// Driver code
var arr = [1, 3, 7];
var n = arr.length;
document.write( minMergeCost(0, n - 1, arr));

</script>  
Producción: 

15

 

Publicación traducida automáticamente

Artículo escrito por DivyanshuShekhar1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *