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 input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
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 test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
For each input file, your program has to write the number quadruplets whose sum is zero.
Sample Input
1
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
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).
这道题目使用了中途相遇法的思想,将最直接的枚举四个数列的时间复杂度为O(N^4)的方法改为,枚举两次并采用HASH,第一次枚举左侧两个队列,将得到的值存进哈希表并记录出现次数,这里要注意的是本题是一个四元关系对,所以相同的数值按不同的元素来计算,第二次,枚举右侧两个队列,查找哈希表,并计算答案。
Liu使用的是二分查找的方法,也是可以的,UVa评测结果是5s左右,而我写的HASH在3s左右。但是代码复杂度明显是二分查找要占优。
附代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAXN (4000+5)
#define HASHNUM (1000003)
struct NODE{
int c,t,ii;
};
int n,total,A[MAXN],B[MAXN],C[MAXN],D[MAXN],H[HASHNUM];
NODE next[MAXN*MAXN];
int HASH(int x){
return abs(x)%HASHNUM;
}
void init_hash_table(){total=1;memset(H,0,sizeof(H));}
void insert_hash_table(int x){
int h=HASH(x);
int u=H[h];
while(u!=0){
if(next[u].c==x){next[u].t++;return;}
u=next[u].ii;
}
next[total].c=x;
next[total].t=1;
next[total].ii=H[h];
H[h]=total;
total++;
}
int get_hash_num(int x){
int h=HASH(x);
int u=H[h];
while(u!=0){
if(next[u].c==x)return next[u].t;
u=next[u].ii;
}
return 0;
}
int main(){
//freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]);
init_hash_table();
sort(A,A+n);sort(B,B+n);sort(C,C+n);sort(D,D+n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
insert_hash_table(A[i]+B[j]);
}
}
long long ans=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int num=get_hash_num(-C[i]-D[j]);
ans+=(long long)num;
}
}
printf("%lld\n",ans);
if(T)printf("\n");
}
//fclose(stdin);
return 0;
}