给定四个包含整数元素和整数和的数组,任务是对四元组进行计数,以使每个元素都从不同的数组中选择,并且所有四个元素的和等于给定的和。
例子:
Input: P[] = {0, 2}, Q[] = {-1, -2}, R[] = {2, 1}, S[] = {2, -1}, sum = 0
Output: 2
(0, -1, 2, -1) and (2, -2, 1, -1) are the required quadruplets.
Input: P[] = {1, -1, 2, 3, 4}, Q[] = {3, 2, 4}, R[] = {-2, -1, 2, 1}, S[] = {4, -1}, sum = 3
Output: 10
方法:本文的Set 1和Set 2中讨论了两种解决此问题的方法。在此,将讨论使用二进制搜索的方法。
选择任意两个数组并计算所有可能的对和,并将它们存储在向量中。现在,选择其他两个数组并计算所有可能的总和,并使用tempSum为每个总和检查使用二进制搜索在先前创建的矢量(排序后)中是否存在sum – temp。
下面是上述方法的实现:
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count
// of the required quadruplets
int countQuadruplets(int arr1[], int n1, int arr2[],
int n2, int arr3[], int n3,
int arr4[], int n4, int value)
{
vector sum1;
vector::iterator it;
vector::iterator it2;
int cnt = 0;
// Take every possible pair sum
// from the two arrays
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
// Push the sum to a vector
sum1.push_back(arr1[i] + arr2[j]);
}
}
// Sort the sum vector
sort(sum1.begin(), sum1.end());
// Calculate the pair sums from
// the other two arrays
for (int i = 0; i < n3; i++) {
for (int j = 0; j < n4; j++) {
// Calculate the sum
int temp = arr3[i] + arr4[j];
// Check whether temp can be added to any
// sum stored in the sum1 vector such that
// the result is the required sum
if (binary_search(sum1.begin(), sum1.end(), value - temp)) {
// Add the count of such values from the sum1 vector
it = lower_bound(sum1.begin(), sum1.end(), value - temp);
it2 = upper_bound(sum1.begin(), sum1.end(), value - temp);
cnt = cnt + ((it2 - sum1.begin()) - (it - sum1.begin()));
}
}
}
return cnt;
}
// Driver code
int main()
{
int arr1[] = { 0, 2 };
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = { -1, -2 };
int n2 = sizeof(arr2) / sizeof(arr2[0]);
int arr3[] = { 2, 1 };
int n3 = sizeof(arr3) / sizeof(arr3[0]);
int arr4[] = { 2, -1 };
int n4 = sizeof(arr4) / sizeof(arr4[0]);
int sum = 0;
cout << countQuadruplets(arr1, n1, arr2, n2,
arr3, n3, arr4, n4, sum);
return 0;
}
输出:
2