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 45Sample Output
5Hint
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).
题目大意:从四列中分别选一个数,问使所选的数加和为0,有多少种选法。
思路:暴力的话复杂度是n^4,肯定超时,用二分(个人认为叫折半枚举更合适)简化的话,复杂度有所降低。这里说下折半枚举,就是分别枚举计算第1、2行 和第3、4行的加和分别是sum1[i]、sum2[i],再通过枚举sum1[i],sum2[i]计算结果。 然而这样仍然超时,这里在查找sum1,sum2时,我们是逐个枚举的,太耗时。下面介绍一个简化复杂度的技巧:利用二分查找。先对sum1、sum2排序,逐个枚举sum1里的数,在sum2中查找 存在几个sum2=(-sum1)。这里用到upper_bound和lower_bound查找。
这里:利用 函数 upper_bound 和lower_bound 的性质 upper_bound(sum1,sum1+n*n,-sum2[i])-lower_bound(sum1,sum1+n*n,-sum2[i]) 表示在sum1中查找值等于(-sum2)的个数。
下面上代码:
#include<stdio.h>
#include<iostream>
#include <map>
#include<set>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
long long sum1[16100000],sum2[16100000],a[4100][4];
int main(){
int n,i,j;
long long sum=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%lld%lld%lld%lld",&a[i][0],&a[i][1],&a[i][2],&a[i][3]);
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
sum1[i*n+j]=a[i][0]+a[j][1];
sum2[i*n+j]=a[i][2]+a[j][3];
}
}
sort(sum1,sum1+n*n); //注意sum1、sum2的范围是n*n
sort(sum2, sum2+n*n);
for(i=0;i<n*n;i++){
sum+=upper_bound(sum1,sum1+n*n,-sum2[i])-lower_bound(sum1,sum1+n*n,-sum2[i]);
//在sum1中查找 值等于(-sum2) 的个数
}
printf("%lld\n",sum);
return 0;
}