Minimice la suma calculada eliminando repetidamente dos elementos cualesquiera e insertando su suma en el Array

Dados N elementos, puede eliminar cualquiera de los dos elementos de la lista, anotar su suma y agregar la suma a la lista. Repita estos pasos mientras haya más de un elemento en la lista. La tarea es minimizar la suma de estas sumas elegidas al final.
Ejemplos: 
 

Entrada: arr[] = {1, 4, 7, 10} 
Salida: 39 
Elija 1 y 4, Sum = 5, arr[] = {5, 7, 10} 
Elija 5 y 7, Sum = 17, arr[] = {12, 10} 
Elija 12 y 10, Suma = 39 , arr[] = {22}
Entrada: arr[] = {1, 3, 7, 5, 6} 
Salida: 48 
 

Enfoque: para minimizar la suma, los elementos que se eligen en cada paso deben ser los elementos mínimos de la lista. Para hacerlo de manera eficiente, se puede usar una cola de prioridad . En cada paso, mientras haya más de un elemento en la lista, elija el mínimo y el segundo mínimo, elimínelos de la lista y agregue su suma a la lista después de actualizar la suma acumulada.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to return the minimized sum
int getMinSum(int arr[], int n)
{
    int i, sum = 0;
 
    // Priority queue to store the elements of the array
    // and retrieve the minimum element efficiently
    priority_queue<int, vector<int>, greater<int> > pq;
 
    // Add all the elements
    // to the priority queue
    for (i = 0; i < n; i++)
        pq.push(arr[i]);
 
    // While there are more than 1 elements
    // left in the queue
    while (pq.size() > 1)
    {
 
        // Remove and get the minimum
        // element from the queue
        int min = pq.top();
 
        pq.pop();
 
        // Remove and get the second minimum
        // element (currently minimum)
        int secondMin = pq.top();
         
        pq.pop();
 
        // Update the sum
        sum += (min + secondMin);
 
        // Add the sum of the minimum
        // elements to the queue
        pq.push(min + secondMin);
    }
 
    // Return the minimized sum
    return sum;
}
 
// Driver code
int main()
{
 
    int arr[] = { 1, 3, 7, 5, 6 };
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << (getMinSum(arr, n));
}
 
// This code is contributed by mohit

Java

// Java implementation of the approach
import java.util.PriorityQueue;
 
class GFG
{
 
    // Function to return the minimized sum
    static int getMinSum(int arr[], int n)
    {
        int i, sum = 0;
 
        // Priority queue to store the elements of the array
        // and retrieve the minimum element efficiently
        PriorityQueue<Integer> pq = new PriorityQueue<>();
 
        // Add all the elements
        // to the priority queue
        for (i = 0; i < n; i++)
            pq.add(arr[i]);
 
        // While there are more than 1 elements
        // left in the queue
        while (pq.size() > 1)
        {
 
            // Remove and get the minimum
            // element from the queue
            int min = pq.poll();
 
            // Remove and get the second minimum
            // element (currently minimum)
            int secondMin = pq.poll();
 
            // Update the sum
            sum += (min + secondMin);
 
            // Add the sum of the minimum
            // elements to the queue
            pq.add(min + secondMin);
        }
 
        // Return the minimized sum
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 7, 5, 6 };
        int n = arr.length;
        System.out.print(getMinSum(arr, n));
    }
}

Python3

# Python3 implementation of the approach
 
# importing heapq python module
# for implementing min heap
import heapq
 
# Function to return the minimized sum
 
 
def getMinSum(arr, n):
    summ = 0
    # Heap to store the elements of the array
    # and retrieve the minimum element efficiently
    pq = arr
    # creating min heap from array pq
    heapq.heapify(pq)
    # While there are more than 1 elements
    # left in the queue
    while (len(pq) > 1):
        # storing minimum element (root of min heap)
        # into minn
        minn = pq[0]
        # replacing root with last element and
        # deleting last element from min heap
        # as per deleting procedure for HEAP
        pq[0] = pq[-1]
        pq.pop()
        # maintaining the min heap property
        heapq.heapify(pq)
        # again storing minimum element (root of min heap)
        # into secondMin
        secondMin = pq[0]
        # again replacing root with last element and
        # deleting last element as per heap procedure
        pq[0] = pq[-1]
        pq.pop()
        # Update the sum
        summ += (minn+secondMin)
        # appending the summ as last element of min heap
        pq.append(minn+secondMin)
        # again maintaining the min heap property
        heapq.heapify(pq)
    return summ
 
 
# Driver Code
if __name__ == "__main__":
    arr = [1, 3, 7, 5, 6]
    n = len(arr)
    print(getMinSum(arr, n))
'''Code is written by RAJAT KUMAR [GLAU]'''

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to return the minimized sum
  static int getMinSum(int[] arr, int n)
  {
    int i, sum = 0;
 
    // Priority queue to store the elements of the array
    // and retrieve the minimum element efficiently
    List<int> pq = new List<int>();
 
    // Add all the elements
    // to the priority queue
    for (i = 0; i < n; i++)
    {
      pq.Add(arr[i]);
    }
 
    // While there are more than 1 elements
    // left in the queue
    while(pq.Count > 1)
    {
      pq.Sort();
 
      // Remove and get the minimum
      // element from the queue
      int min = pq[0];
      pq.RemoveAt(0);
 
      // Remove and get the second minimum
      // element (currently minimum)
      int secondMin = pq[0];
      pq.RemoveAt(0);
 
      // Update the sum
      sum += (min + secondMin);
 
      // Add the sum of the minimum
      // elements to the queue
      pq.Add(min + secondMin);
    }
 
    // Return the minimized sum
    return sum;
  }
 
  // Driver code
  static public void Main ()
  {
    int[] arr = { 1, 3, 7, 5, 6 };
    int n = arr.Length;
    Console.WriteLine(getMinSum(arr, n));
  }
}
 
// This code is contributed by avanitrachhadiya2155

Javascript

<script>
 
// JavaScript implementation of the approach
 
    // Function to return the minimized sum
    function getMinSum(arr,n)
    {
        let i, sum = 0;
  
        // Priority queue to store the elements of the array
        // and retrieve the minimum element efficiently
        let pq = [];
  
        // Add all the elements
        // to the priority queue
        for (i = 0; i < n; i++)
            pq.push(arr[i]);
  
        // While there are more than 1 elements
        // left in the queue
        while (pq.length > 1)
        {
  
            // Remove and get the minimum
            // element from the queue
            let min = pq.shift();
  
            // Remove and get the second minimum
            // element (currently minimum)
            let secondMin = pq.shift();
  
            // Update the sum
            sum += (min + secondMin);
  
            // Add the sum of the minimum
            // elements to the queue
            pq.push(min + secondMin);
        }
  
        // Return the minimized sum
        return sum;
    }
     
    // Driver code
    let arr=[1, 3, 7, 5, 6];
    let n = arr.length;
    document.write(getMinSum(arr, n));
 
     
 
// This code is contributed by rag2127
 
</script>
Producción: 

48

 

Complejidad de tiempo: O(N * log(N))
Espacio auxiliar: O(N) 

Publicación traducida automáticamente

Artículo escrito por bestharadhakrishna 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 *