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).
题意:题意很好理解,就是abcd序列里面,各选一个数字相加为0的情况个数,这道题因为数据很多,就把abcd分成两个部分,ab一个部分求和排序,cd一个部分,然后再用二分求两个部分的和为0的情况,这里不能只是找到是否存在,还要计算符合要求的情况个数
代码:
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include<iostream>
using namespace std;
int ab[4010*4010],cd[4010*4010];
int main()
{
int n,i,k,j,count,a[4010],b[4010],c[4010],d[4010];
while(cin>>n)
{
for(i=0;i<n;i++)
cin>>a[i]>>b[i]>>c[i]>>d[i];
int cot1=0;
int cot2=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
ab[cot1++]=a[i]+b[j];
cd[cot2++]=-(c[i]+d[j]);
}
}
sort(cd,cd+cot2);
count=0;
for(i=0;i<cot1;i++)
{
int left=0;
int right=n*n-1;
while(left<=right)
{
int mid=(left+right)/2;
if(ab[i]==cd[mid])
{
count++;
for(k=mid+1;k<cot2;k++)
{
if(ab[i]==cd[k])
count++;
else
break;
}
for(k=mid-1;k>=0;k--)
{
if(ab[i]==cd[k])
count++;
else
break;
}
break;
}
else if(ab[i]<cd[mid])
right=mid-1;
else
left=mid+1;
}
}
cout<<count<<endl;
}
return 0;
}