The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .
Input
The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 2 28 ) that belong respectively to A, B, C and D .
Output
For each input file, your program has to write the number quadruplets whose sum is zero.
Sample Input
6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45
Sample Output
5
Hint
Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).
题意:给你4个数组a,b,c,d,问从每一个数组中任选一个元素,如果这4个元素的和为0,则说这4个数为quadruplet,问总共有多少组quadruplet。
题解:纯枚举的话,时间复杂度为o(n^4),肯定会超时,所以用二分的思想做这道题。我们想到既然有四列,那么我们可以分别计算前两列和后两列的和(只需要nn2次运算) 然后对后两列的和排序,那么我们对于每一个前两列的和都可以二分找到后两列的和中与之相加为0的个数,这样的复杂度就是O(nnlog(n))是可以接受的。
在这里插入代码片
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 5000;
const int maxm = 25000000;
long long a[maxn], b[maxn], c[maxn], d[maxn];
long long sum2[maxm];
int main()
{
int n;
long long num;
while (scanf ("%d", &n) != EOF) {
num = 0;
for (int i = 0; i < n; i++) {
scanf ("%lld%lld%lld%lld", &a[i], &b[i], &c[i], &d[i]);
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sum2[cnt++] = c[i] + d[j];
}
}
sort (sum2, sum2 + cnt);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
long long sum = a[i] + b[j];
num += upper_bound(sum2, sum2 + cnt, -sum) - lower_bound(sum2, sum2 + cnt, -sum);//这是算法竞赛中STL中的
}
}
printf ("%lld\n", num);
}
return 0;
}