给定的阵列ARR [整数N对(A,B),其中N是偶数,则任务是找到使得从所有的对值A和B被选择恰好(N / 2中选择N个元素的最小总和的] )次。
例子:
Input: N = 4, arr[][] = { {7, 20}, {300, 50}, {30, 200}, {30, 20} }
Output: 107
Explanation:
Choose value-A from 1st pair = 7.
Choose value-B from 2nd pair = 50.
Choose value-A from 3rd pair = 30.
Choose value-B from 4th pair = 20.
The minimum sum is 7 + 50 + 30 + 20 = 107.
Input: N = 4, arr[][] = { {10, 20}, {400, 50}, {30, 200}, {30, 20} }
Output: 110
Explanation:
Choose value-A from 1st pair = 10.
Choose value-B from 2nd pair = 50.
Choose value-A from 3rd pair = 30.
Choose value-B from 4th pair = 20.
The minimum sum is 10 + 50 + 30 + 20 = 110.
方法:此问题可以使用贪婪方法解决。步骤如下:
- 对于给定数组中的每个对(A,B) ,将(B – A)的值和相应的索引存储在临时数组中(例如temp [] )。值(B – A)实际上定义了如果为每个元素在B上选择A,则将成本最小化。
- 目的是使总成本最小化。因此,请按降序对数组temp []进行排序。
- 通过选择一个拾取从阵列临时[]第一N / 2个元素作为当选择了在B A第一N / 2个元素将具有最大总和。
- 对于剩余的N / 2个元素,请选择B,因为可以将值的总和最小化。
下面是上述方法的实现:
// C++ program for the above approach
#include
using namespace std;
// Function to choose the elements A
// and B such the sum of all elements
// is minimum
int minSum(int arr[][2], int n)
{
// Create an array of pair to
// store Savings and index
pair temp[n];
// Traverse the given array of pairs
for (int i = 0; i < 2 * n; i++) {
// Sum minimized when A
// is chosen over B for
// i-th element.
temp[i].first = arr[i][1]
- arr[i][0];
// Store index for the
// future reference.
temp[i].second = i;
}
// Sort savings array in
// non-increasing order.
sort(temp, temp + 2 * n,
greater >());
// Storing result
int res = 0;
for (int i = 0; i < 2 * n; i++) {
// First n elements choose
// A and rest choose B
if (i < n)
res += arr[temp[i].second][0];
else
res += arr[temp[i].second][1];
}
// Return the final Sum
return res;
}
// Driver Code
int main()
{
// Given array of pairs
int arr[4][2] = { { 7, 20 },
{ 300, 50 },
{ 30, 200 },
{ 30, 20 } };
// Function Call
cout << minSum(arr, 2);
}
107
时间复杂度: O(N * log(N))
辅助空间复杂度: O(N)