POJ 2785 4 Values whose Sum is 0(暴力枚举的优化策略)

时间:2022-10-31 19:54:26

题目链接:

https://cn.vjudge.net/problem/POJ-2785

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).
 /*
问题 给出n行的4个数,这四列数分别是A,B,C,D的集合,问有多少组ABCD相加和为0
解题思路 刚开始没读懂题就开始写了,没想到题意是另一个意思,还是按练习要求做题吧。
读懂了题,脑子里马上跳出4重循环,又一看n最大为4000,还是放弃吧。
看了一下分析,先将a+b的结果与其出现的次数放在map容器里,再将c+d的结果与其出现的次数放在map容器里,最后查找一下,
如果存在则累计结果。但是超时,原因是常数较大时使用map也可能超时。
随后在网上看到一种更为巧妙的解法,将C和D的所有结果存放在一个一维数组中,再将其排序,遍历A+B的和,累加在这个二维数组
中的个数即可。
*/ /*解法一 超时!!!
#include<cstdio>
#include<iostream>
#include<map>
using namespace std; int main(){
int T,n,cou,i,j,a[4010],b[4010],c[4010],d[4010];
map<int,int> m1,m2; while(scanf("%d",&n) != EOF)
{
j=0;
for(i=1;i<=n;i++){
scanf("%d%d%d%d",&a[j],&b[j],&c[j],&d[j]);
j++;//不能缩放在上面的一句
} for(i=0;i<n;i++){
for(j=0;j<n;j++){
m1[ a[i]+b[j] ]++;
}
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
m2[ -1*(c[i]+d[j] ) ]++;
}
} map<int,int>::iterator it1,it2;
int ans=0;
for(it1=m1.begin(); it1 != m1.end(); it1++){
it2=m2.find(it1->first);
if(it2 != m2.end()){
ans += (it1->second * it2->second);
}
}
printf("%d\n",ans);
}
return 0;
}*/
//解法二
#include<cstdio>
#include<algorithm>
using namespace std; int cd[*];//一维数组当二维数组用 int main(){
int T,n,cou,i,j,a[],b[],c[],d[],sumab;
long long ans;
while(scanf("%d",&n) != EOF)
{
for(i=;i<n;i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]); for(i=;i<n;i++){
for(j=;j<n;j++){
cd[i*n+j]=c[i]+d[j];
}
} sort(cd,cd+n*n); ans=;
for(i=;i<n;i++){
for(j=;j<n;j++){
sumab=-*(a[i]+b[j]);
ans += upper_bound(cd,cd+n*n,sumab) - lower_bound(cd,cd+n*n,sumab);
//使用参数,起点+终点+目标值
}
} printf("%lld\n",ans);
}
return ;
}