# 第四十二题 UVA1152 和为0的4个值 4 Values whose Sum is 0

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 × B × C × 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, your program has to write the number quadruplets whose sum is zero.
The outputs of two consecutive cases will be separated by a blank line.
Sample Input
1
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
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).

T行，一行一个整数，代表T组测试数据的答案。

n<=4000，集合中任意一个数绝对值小于等于2^28。

/*

Get_L Get_R 两个函数可以用 C++的 upper_bound 和 lower_Bound 代替

*/

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define Maxn 4002

using namespace std;
int A[Maxn],B[Maxn],C[Maxn],D[Maxn];
int S[Maxn * Maxn],cnt;

x = 0; register char c = getchar(); int f = 1; // register 寄存器
while(c > '9' || c < '0') { c = getchar(); f = -1; }
while(c >= '0' && c <= '9') { x = (x * 10 ) + c - '0'; c = getchar(); }
x *= f;
}

int main(int argc,char* argv[]) {
int n,T; scanf("%d",&T);
while(T--) {
scanf("%d",&n); cnt = 0;
for(int i=1; i<=n; i++) scanf("%d %d %d %d",&A[i],&B[i],&C[i],&D[i]);
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++) S[++cnt] = A[i] + B[j];
sort(S + 1, S + cnt + 1);
long long Ans = 0;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
Ans += upper_bound(S + 1,S + cnt + 1,-C[i]-D[j]) - lower_bound(S + 1,S + cnt + 1, -C[i]-D[j]) ;
printf("%lld\n",Ans);
if(T) printf("\n");
}
return 0;
}


lower_bound(起始地址，结束地址，要查找的数值) 返回的是数值 第一个 出现的位置。
upper_bound(起始地址，结束地址，要查找的数值) 返回的是数值 最后一个 出现的位置。
binary_search(起始地址，结束地址，要查找的数值) 返回的是是否存在这么一个数，是一个bool值。

1 函数lower_bound() 参考：有关lower_bound()函数的使用

2 函数upper_bound()

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客