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 input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
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 228 ) that belong respectively to A, B, C and D .
Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
For each input file, your program has to write the number quadruplets whose sum is zero.
Sample Input
16-45 22 42 -16-41 -27 56 30-36 53 -37 77
26 -38 -10 62-36 30 -75 -46
-32 -54 -6 45
Sample Output
5
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <iostream>
#include <math.h>
using namespace std;
const int Max = 4000 + 10;
int a[Max], b[Max], c[Max], d[Max];
int mem[Max*Max];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);
}
int k = 0;
for(int i = 0; i < n; i++)///将 a+b 的值存入数组中
{
for(int j = 0; j < n; j++)
{
mem[k++] = a[i] + b[j];
}
}
sort(mem,mem+k);
int ans = 0;
for(int i = 0; i < n; i++)///将排序后的 a+b 的值进行二分查找,如果 a+b 与 (-c-d) 相同,则将结果加 1 .
for(int j = 0; j < n; j++)
{
ans += upper_bound(mem,mem+k,-c[i]-d[j]) - lower_bound(mem,mem+k,-c[i]-d[j]);
}
printf("%d\n",ans);
if(t)
printf("\n");
}
return 0;
}