4 Values whose Sum is 0
Time Limit: 15000MS | Memory Limit: 228000K | |
Total Submissions: 29083 | Accepted: 8820 | |
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).
两种方法:
方法一:利用函数的增减性
#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <map>
using namespace std;
int a[4001],b[4001],c[4001],d[4001];
int ab[4000*4000+1],cd[4000*4000+1];
int main(){
int n;
while(~scanf("%d",&n)){
int sum=0,num,x=n*n-1;
for(int i=0;i<n;i++)
scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);
int l=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
ab[l++]=a[i]+b[j];
}
l=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
cd[l++]=c[i]+d[j];
}
sort(ab,ab+n*n);
sort(cd,cd+n*n);
for(int i=0;i<n*n;i++){
while(x>=0&&ab[i]+cd[x]>0)
x--;
if(x<0) break;
num=x;
while(ab[i]+cd[num]==0&&num>=0){
sum++;
num--;
}
}
printf("%d\n",sum);
}
return 0;
}
方法二:二分查找(慢)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[4001],b[4001],c[4001],d[4001];
int ab[4000*4000+1],cd[4000*4000+1];
int k2;
int check(int x)
{
int left=1,right=k2-1,mid;
while (left<=right)
{
mid=(left+right)/2;
if (x==cd[mid])
{
int w=0,e=mid;
while (x==cd[e]&&e<k2)
e++,w++;
e=mid-1;
while (x==cd[e]&&e>0)
e--,w++;
return w;
}
else if (x<cd[mid])
right=mid-1;
else
left=mid+1;
}
return 0;
}
int main()
{
int t,i,j,q;
while (~scanf("%d",&t))
{
for (i=1;i<=t;i++)
scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);
memset(ab,0,sizeof(ab));
memset(cd,0,sizeof(cd));
int k1=1,sum=0;
k2=1;
for (i=1;i<=t;i++)
{
for (j=1;j<=t;j++)
{
ab[k1++]=a[i]+b[j];
cd[k2++]=-(c[i]+d[j]);
}
}
sort(cd+1,cd+k2);
for (i=1;i<k1;i++)
sum+=check(ab[i]);
printf("%d\n",sum);
}
return 0;
}