**4 Values whose Sum is 0 *斜体样式
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个数组a,b,c,d,问从每一个数组中任选一个元素,如果这4个元素的和为0,则说这4个数为quadruplet,问总共有多少组quadruplet。
题解:纯枚举的话,时间复杂度为o(n^4),肯定会超时,所以用二分的思想做这道题。我们想到既然有四列,那么我们可以分别计算前两列和后两列的和(只需要nn2次运算) 然后对后两列的和排序,那么我们对于每一个前两列的和都可以二分找到后两列的和中与之相加为0的个数,这样的复杂度就是O(nnlog(n))是可以接受的。
在这里插入代码片
#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
int a[4005],b[4005],c[4005],d[4005];
long long s1[16000005];
long long s2[16000005];
int k2=1;
int n;
int sum;
void bsearch(int t)
{
int u=1;
int v=k2;
while(u<=v)
{
int m=(u+v)/2;
if(s2[m]==t)
{
sum++;
for(int i=m+1;i<=k2;i++)
{
if(s2[i]==t)
{
sum++;
}
else
{
break;
}
}
for(int i=m-1;i>0;i--)
{
if(s2[i]==t)
{
sum++;
}
else
{
break;
}
}
return;
}
else if(t<s2[m])
{
v=m-1;
}
else
{
u=m+1;
}
}
}
int main()
{
while(~scanf("%d",&n))
{
long long k1=1;
for(int i=1;i<=n;i++)
{
scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
s1[k1++]=a[i]+b[j];
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
s2[k2++]=c[i]+d[j];
}
}
sum=0;
sort(s2+1,s2+k2);
k2--;
for(int i=1;i<k1;i++)
{
bsearch(-s1[i]);
}
printf("%d\n",sum);
}
return 0;
}