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 228 ) 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.
#include<iostream>#include<algorithm>#include<cstdio>
using namespace std;typedeflonglong ll;
ll a[4005],b[4005],c[4005],d[4005],sum1[4005*4005],sum2[4005*4005];intmain(){int n;
cin>>n;for(int i =0;i<n;i++){scanf("%lld %lld %lld %lld",&a[i],&b[i],&c[i],&d[i]);}
ll k =0;for(int i =0;i<n;i++){for(int j =0;j<n;j++){
sum1[k]=a[i]+b[j];
sum2[k]=c[i]+d[j];
k++;}}sort(sum1,sum1+k);int ans =0;for(int i =0;i<k;i++){
ll num =lower_bound(sum1,sum1+k,-sum2[i])-sum1;if(sum1[num]==-sum2[i]){
ans+=upper_bound(sum1,sum1+k,-sum2[i])-sum1 - num;//上下界作差,有可能同一个sum1中的元素在sum2中有多组答案相匹配。}}printf("%d",ans);}