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).
题目大意:从a,b,c,d四个序列里分别出一个数,使所加和为0.
思路:将前两个序列合并成一个,后两个合并为一个,使用折半枚举的方法,所以要看满足条件的有几个,使用STL中的upper_bound(>)和lower_bound(>=)函数。
/*
先将a数组与b数组进行合并为f数组,
再枚举b和c相加的和的相反数在f中寻找
lower_bound函数找到第一个>=的值
upper_bound函数找到第一个>的值
*/
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[4010],b[4010],c[4010],d[4010];
int f[16000010];
int n;
int lower_bound(int y)
{
int l,r,m;
l=0;
r=n*n-1;
while(l<=r)
{
m=(l+r)/2;
if(f[m]>=y)//*****
r=m-1;
else
l=m+1;
}
return l;
}
/*
l为最后的返回值
lower_bound为了找第一个>=的值
所以当满足条件是l不可以变
*/
int upper_bound(int x)
{
int l,r,m;
l=0;
r=n*n-1;
while(l<=r)
{
m=(l+r)/2;
if(f[m]<=x)//*****
l=m+1;
else
r=m-1;
}
return l;
}
/*
l为最后的返回值
upper_bound函数找到第一个>的值
当满足条件的时候l不可以改变
*/
int main()
{
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
memset(d,0,sizeof(d));
memset(f,0,sizeof(f));
for(int i=0; i<n; i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
int i,j;
for(i=0; i<n; i++)
{
for( j=0; j<n; j++)
{
f[i*n+j]=a[i]+b[j];
}
}
sort(f,f+n*n);
int ans=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
int s=c[i]+d[j];
ans+=upper_bound(-s)-lower_bound(-s);
}
}
printf("%d\n",ans);
}
return 0;
}