📌  相关文章
📜  通过重复地将对替换为总和的一半,以最小化剩余的数组元素

📅  最后修改于: 2021-05-17 04:40:24             🧑  作者: Mango

给定一个数组arr [],其中包含前N个自然数的排列。在一个操作中,从阵列中删除一对(X,Y) ,然后将(X + Y + 1)/ 2插入阵列。任务是通过精确地执行给定的操作N – 1次和N – 1对,找到可以保留在数组中的最小数组元素。如果存在多个解决方案,则打印其中任何一种。

例子:

方法:可以使用贪婪技术解决问题。请按照以下步骤解决问题:

  • 初始化一个数组,例如, pairsArr [],以存储可以通过执行给定操作选择的所有对。
  • 创建一个优先级队列,例如说pq,以将所有数组元素存储在优先级队列中。
  • 横动PQ而留在PQ计数元件是大于1且在每个操作弹出顶部的两个元素PQ(X,Y),商店(X,Y)pairsArr [],然后插入具有值的元素(X + Y更大+1)/ 2pq中
  • 最后,打印留在pqpairArr []中的元素的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to print the smallest element left
// in the array and the pairs by given operation
void smallestNumberLeftInPQ(int arr[], int N)
{
 
    // Stores array elements and return
    // the minimum element of arr[] in O(1)
    priority_queue pq;
 
    // Stores all the pairs that can be
    // selected by the given operations
    vector > pairsArr;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
        pq.push(arr[i]);
    }
 
    // Traverse pq while count of elements
    // left in pq greater than 1
    while (pq.size() > 1) {
 
        // Stores top element of pq
        int X = pq.top();
 
        // Pop top element of pq
        pq.pop();
 
        // Stores top element of pq
        int Y = pq.top();
 
        // Pop top element of pq
        pq.pop();
 
        // Insert (X + Y + 1) / 2 in pq
        pq.push((X + Y + 1) / 2);
 
        // Insert the pair  (X, Y)
        // in pairsArr[]
        pairsArr.push_back({ X, Y });
    }
 
    // Print the element left in pq
    // by performing the given operations
    cout << "{" << pq.top() << "}, ";
 
    // Stores count of elements
    // in pairsArr[]
    int sz = pairsArr.size();
 
    // Print all the pairs that can
    // be selected in given operations
    for (int i = 0; i < sz; i++) {
 
        // If i is the first
        // index of pairsArr[]
        if (i == 0) {
            cout << "{ ";
        }
 
        // Print current pairs of pairsArr[]
        cout << "(" << pairsArr[i].first
             << ", " << pairsArr[i].second << ")";
 
        // If i is not the last index
        // of pairsArr[]
        if (i != sz - 1) {
            cout << ", ";
        }
 
        // If i is the last index
        // of pairsArr[]
        if (i == sz - 1) {
            cout << " }";
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    smallestNumberLeftInPQ(arr, N);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG
{
    static class pair
    {
        int first, second;
        public pair(int first, int second) 
        {
            this.first = first;
            this.second = second;
        }   
    }
 
// Function to print the smallest element left
// in the array and the pairs by given operation
static void smallestNumberLeftInPQ(int arr[], int N)
{
 
    // Stores array elements and return
    // the minimum element of arr[] in O(1)
    PriorityQueue pq = new PriorityQueue<>((x, y) ->
                                    Integer.compare(y, x));
 
    // Stores all the pairs that can be
    // selected by the given operations
    Vector pairsArr = new Vector<>();
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
    {
        pq.add(arr[i]);
    }
 
    // Traverse pq while count of elements
    // left in pq greater than 1
    while (pq.size() > 1) {
 
        // Stores top element of pq
        int X = pq.peek();
 
        // Pop top element of pq
        pq.remove();
 
        // Stores top element of pq
        int Y = pq.peek();
 
        // Pop top element of pq
        pq.remove();
 
        // Insert (X + Y + 1) / 2 in pq
        pq.add((X + Y + 1) / 2);
 
        // Insert the pair  (X, Y)
        // in pairsArr[]
        pairsArr.add(new pair( X, Y ));
    }
 
    // Print the element left in pq
    // by performing the given operations
    System.out.print("{" +  pq.peek()+ "}, ");
 
    // Stores count of elements
    // in pairsArr[]
    int sz = pairsArr.size();
 
    // Print all the pairs that can
    // be selected in given operations
    for (int i = 0; i < sz; i++) {
 
        // If i is the first
        // index of pairsArr[]
        if (i == 0) {
            System.out.print("{ ");
        }
 
        // Print current pairs of pairsArr[]
        System.out.print("(" +  pairsArr.get(i).first
            + ", " +  pairsArr.get(i).second+ ")");
 
        // If i is not the last index
        // of pairsArr[]
        if (i != sz - 1) {
            System.out.print(", ");
        }
 
        // If i is the last index
        // of pairsArr[]
        if (i == sz - 1) {
            System.out.print(" }");
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 1 };
    int N = arr.length;
    smallestNumberLeftInPQ(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
 
# Function to prthe smallest
# element left in the array
# and the pairs by given operation
def smallestNumberLeftInPQ(arr, N):
 
    # Stores array elements and
    # return the minimum element
    # of arr[] in O(1)
    pq = []
 
    # Stores all the pairs that can
    # be selected by the given operations
    pairsArr = []
 
    # Traverse the array arr[]
    for i in range(N):
        pq.append(arr[i])
    pq = sorted(pq)
 
    # Traverse pq while count of
    # elements left in pq greater
    # than 1
    while (len(pq) > 1):
 
        # Stores top element of pq
        X = pq[-1]
         
        del pq[-1]
 
        # Stores top element of pq
        Y = pq[-1]
 
        # Pop top element of pq
        del pq[-1]
 
        # Insert (X + Y + 1) / 2
        # in pq
        pq.append((X + Y + 1) // 2)
 
        # Insert the pair  (X, Y)
        # in pairsArr[]
        pairsArr.append([X, Y])
 
        pq = sorted(pq)
 
    # Print element left in pq
    # by performing the given
    # operations
    print("{", pq[-1], "}, ",
          end = "")
 
    # Stores count of elements
    # in pairsArr[]
    sz = len(pairsArr)
 
    # Print the pairs that can
    # be selected in given operations
    for i in range(sz):
 
        # If i is the first
        # index of pairsArr[]
        if (i == 0):
            print("{ ", end = "")
 
        # Print pairs of pairsArr[]
        print("(", pairsArr[i][0], ",",
              pairsArr[i][1], ")", end = "")
 
        # If i is not the last index
        # of pairsArr[]
        if (i != sz - 1):
            print(end = ", ")
 
        # If i is the last index
        # of pairsArr[]
        if (i == sz - 1):
            print(end = " }")
 
# Driver Code
if __name__ == '__main__':
   
    arr = [3, 2, 1]
    N = len(arr)
    smallestNumberLeftInPQ(arr, N)
 
# This code is contributed by Mohit Kumar 29


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
public class pair
{
    public int first, second;
     
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to print the smallest element left
// in the array and the pairs by given operation
static void smallestNumberLeftInPQ(int[] arr,
                                   int N)
{
     
    // Stores array elements and return
    // the minimum element of []arr in O(1)
    List pq = new List();
     
    // Stores all the pairs that can be
    // selected by the given operations
    List pairsArr = new List();
 
    // Traverse the array []arr
    for(int i = 0; i < N; i++)
    {
        pq.Add(arr[i]);
    }
    pq.Sort();
    pq.Reverse();
     
    // Traverse pq while count of elements
    // left in pq greater than 1
    while (pq.Count > 1)
    {
         
        // Stores top element of pq
        int X = pq[0];
 
        // Pop top element of pq
        pq.RemoveAt(0);
 
        // Stores top element of pq
        int Y = pq[0];
 
        // Pop top element of pq
        pq.RemoveAt(0);
 
        // Insert (X + Y + 1) / 2 in pq
        pq.Add((X + Y + 1) / 2);
        pq.Sort();
        pq.Reverse();
         
        // Insert the pair  (X, Y)
        // in pairsArr[]
        pairsArr.Add(new pair(X, Y));
    }
 
    // Print the element left in pq
    // by performing the given operations
    Console.Write("{" + pq[0] + "}, ");
 
    // Stores count of elements
    // in pairsArr[]
    int sz = pairsArr.Count;
 
    // Print all the pairs that can
    // be selected in given operations
    for(int i = 0; i < sz; i++)
    {
         
        // If i is the first
        // index of pairsArr[]
        if (i == 0)
        {
            Console.Write("{ ");
        }
 
        // Print current pairs of pairsArr[]
        Console.Write("(" + pairsArr[i].first + ", " +
                            pairsArr[i].second + ")");
 
        // If i is not the last index
        // of pairsArr[]
        if (i != sz - 1)
        {
            Console.Write(", ");
        }
 
        // If i is the last index
        // of pairsArr[]
        if (i == sz - 1)
        {
            Console.Write(" }");
        }
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 3, 2, 1 };
    int N = arr.Length;
     
    smallestNumberLeftInPQ(arr, N);
}
}
 
// This code is contributed by aashish1995


输出:
{2}, { (3, 2), (3, 1) }

时间复杂度: O(N * log(N))

辅助空间: O(N)