4 Values whose Sum is 0
Time Limit: 15000MS | Memory Limit: 228000K | |
Total Submissions: 16271 | Accepted: 4718 | |
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 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).
Source
先枚举出所有a[i]+b[j]的值,存到哈希表中。
再枚举所有tmp=c[i]+d[j]的值,检查-tmp是否在哈希表中,返回个数。
3200+ms.如果用排序加二分查找5000+ms。。。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define maxn 4001
#define M 21331131
const int inf =(1<<29);
int a[maxn], b[maxn],c[maxn],d[maxn];
int n;
struct node
{
node(){}
node(int v, int n, int c){val = v; next =n; cnt = c;}
int val;
int next;
int cnt;
};
node h[maxn*maxn];
int first[M], top; //邻接表写法,first为表头指针
void insert(int v)
{
int pos = (v+inf)%M;
int tmp = -1;
for(int i = first[pos]; i!=-1; i=h[i].next)
if(h[i].val == v){
h[i].cnt++;
return;
}
h[top] = node(v, first[pos], 1);
first[pos] = top++;
}
int find(int v)
{
int pos = (v+inf)%M;
for(int i = first[pos]; i != -1; i=h[i].next)
if(v == h[i].val)
return h[i].cnt;
return 0;
}
int main()
{
while(scanf("%d", &n)!=EOF){
memset(first, -1, sizeof(first));
top = 0;
for(int i = 0; i < n; i++)
scanf("%d%d%d%d", a+i, b+i, c+i, d+i);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
insert(a[i]+b[j]);
long long ans = 0;
int tmp;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
tmp = c[i]+d[j];
ans += find(-tmp);
}
printf("%lld\n", ans);
}
return 0;
}