Time Limit: 15000MS | Memory Limit: 228000K | |
Total Submissions: 31408 | Accepted: 9586 | |
Case Time Limit: 5000MS |
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 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.
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).
Source
题目大意:现在给你四个集合,每个集合中有N个数,问你从他们当中每个取一个数组成的数的代数和为0的情况有多少种
思路:这个题目本来我一开15S我就想着用暴力整一下,用一个循环弄一弄,最后发现,这个东西在后面查找时候完全可以用一个二分查找来优化时间。
需要注意的是,因为这个二分查找找到的我们需要的结果,但是他的前一位或者后一位还有可能是我们需要的结果,所以在正好相加为0的情况下再进行一步判断增加结果
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=4010;
int a[maxn],b[maxn],c[maxn],d[maxn];
int sum[maxn*maxn],sum2[maxn*maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
}
int k=0;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
sum[k]=a[i]+b[j];
sum2[k]=c[i]+d[j];
k++;
}
}
sort(sum,sum+k);
//sort(sum2,sum2+k);
int ans=0;
for(int i=0; i<k; i++)
{
int div=-sum2[i];
int l=0,r=k-1;
while(l<=r)
{
int mid=(l+r)/2;
if(sum[mid]>div)
r=mid-1;
else if(sum[mid]<div)
l=mid+1;
else
{
for(int s=mid; s>=0; s--)
{
if(sum[s]==div)
ans++;
else
break;
}
for(int s=mid+1; s<k; s++)
{
if(sum[s]==div)
ans++;
else
break;
}
break;
}
}
}
cout<<ans<<endl;
}