4 Values whose Sum is 0
Time Limit: 15000MS | Memory Limit: 228000K | |
Total Submissions: 22691 | Accepted: 6869 | |
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
题目大意:给出四列数A,B,C,D,每列中选出一个数啊a,b,c,d,问有多少种情况可以使得a+b+c+d=0。
大致思路:直接用四个循环超时是肯定的,这时可以用折半的方法,先求a[i]+b[i],再求c[i]+d[i],用二分找出c[i]+d[i]中满足的情况。详见代码(本题还能用hash做)
#include<iostream> #include<cstring> #include<algorithm> #include<cstdio> using namespace std; #define maxn 4005 int a[maxn],b[maxn],c[maxn],d[maxn]; int ab[maxn*maxn],cd[maxn*maxn]; int main() { int i,j,N,lo,hi,mid,cou=0,p=0; cin>>N; for(i=0;i<N;i++) cin>>a[i]>>b[i]>>c[i]>>d[i]; for(i=0;i<N;i++) for(j=0;j<N;j++) { ab[p]=a[i]+b[j]; p++; } sort(ab,ab+N*N); p=0; for(i=0;i<N;i++) for(j=0;j<N;j++) { cd[p]=c[i]+d[j]; p++; } sort(cd,cd+N*N); for(i=0;i<p;i++) { lo=0;hi=p;//从p-1和p开始二分都行 while(lo<hi)//这个循环会找到一个与要找的数相等的最小下标 { mid=(lo+hi)/2; if(ab[mid]<-cd[i])//因为是排好序的,所以可以直接利用数组下标二分 lo=mid+1; else hi=mid; } while(ab[lo]==-cd[i]&&lo<p)//判断lo和lo之后是否相等,因为可能会有数据相同,注意lo<p!!! { cou++; lo++; } } cout<<cou<<endl; return 0; }