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

📅  最后修改于: 2021-10-26 05:42:48             🧑  作者: Mango

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

例子:

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

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

下面是上述方法的实现:

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 print 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


Javascript


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

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

辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程