Description
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).
解题思路:
枚举加二分,找4个数相加等于0的情况,首先将a[i]+bji]和c[i]+d[j]存放在两个数组中这样在循环时就只用外层数组一个循环,内层数组二分(内层数组要排序),
代码:
#include <iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
#define N 4002
long long int a[N]; long long int b[N];
long long int c[N]; long long int d[N];
int e[16000005]; int f[16000005];
int main()
{
//freopen("aaa.txt","r",stdin);
long long int n,i,j,l,r,mid,num,p,n1;
while(scanf("%lld",&n)!=EOF) {
for(i=0;i<n;i++)
scanf("%lld%lld%lld%lld",&a[i],&b[i],&c[i],&d[i]);
num=0; n1=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{e[n1]=a[i]+b[j];f[n1]=c[i]+d[j];n1++;}
sort(e,e+n1); //sort(f,f+n1);
for(i=0;i<n1;i++)
{
l=0; r=n1-1;
while(l<=r)
{
mid=(r+l)/2;
if(f[i]+e[mid]==0)
{
num++;
for(p=mid-1;p>=0;p--)
if(e[p]==e[mid]) num++; else break;
for(p=mid+1;p<n1;p++)
if(e[p]==e[mid]) num++; else break;
break;
}
else {
if(f[i]+e[mid]>0)
r=mid-1;
else l=mid+1;
}
}
}
printf("%lld\n",num);
}
return 0;
}