POJ-2785:4 Values whose Sum is 0
来源:POJ
标签:
参考资料:
相似题目:
题目
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 .
输入
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 .
输出
For each input file, your program has to write the number quadruplets whose sum is zero.
输入样例
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
输出样例
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).
题目大意
解题思路
参考代码
#include<stdio.h>
#include<algorithm>
#define MAXN 4005
using namespace std;
int A[MAXN],B[MAXN],C[MAXN],D[MAXN];
int AB[MAXN*MAXN];
int main(){
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 cnt=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
AB[cnt++]=A[i]+B[j];
}
}
sort(AB,AB+cnt);
int ans=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int t=-C[i]-D[j];
ans += upper_bound(AB,AB+cnt,t) - lower_bound(AB,AB+cnt,t);//因为存在AB[]中可能存在相同元素,普通的二分查找不再适用
}
}
printf("%d\n",ans);
return 0;
}