4 Values whose Sum is 0
Time Limit: 15000MS | Memory Limit: 228000K | |
Total Submissions: 14474 | Accepted: 4137 | |
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 .
“和”的问题可总结如下:给定四个列表A,B,C,D里面是整数,计算出有多少四胞胎(A,B,C,D)∈
A x B x C x D,A + B+ C + D=0。在下文中,我们假设所有的列表具有相同的大小为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 .
输入文件的第一行包含列表n的大小(此值可以是大到4000)。然后,我们有n个行分别是A,B,C和D,每个列表4个整数值(以绝对值最大
2
28)。
Output
For each input file, your program has to write the number quadruplets whose sum is zero.
输出有多少个四胞胎T_T
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
hash,一开始也知道就是用前两个的和做表,后两个和找表求和,因为跟前一题同一个思路。。。不过趁机学了一个新的hash方式,跟之前的线性探测不一样,就是用静态的链表,恩。。。这种直接模拟的链表,来解决冲突,然后直接用模大质数来做hash函数,这个方式应该效率蛮高的。主要最坏效率取决于链表长度呗。。。所以肯定用的质数越大,越不容易起冲突效率越高,然后就挑了跟学的那位的质数3999971,其实我印象里过4000000的数组基本就爆了。。。不过我的记性不咋地,如此看来也就能开这么大了。。。哦,由于加和的可能性是4000^4,所以要给输出的ans一个long long型,不然就爆了。。。就数据本身来说有的加和可能性也有4000*4000,所以hash表的长度咋地都不够,肯定要冲突。。。T_T
#include <iostream>
#include<algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAX 4444444
using namespace std;
void insert_hash(int s);
int find_hash(int s);
int hash_i(int s);
struct LINK{
int val;
int next;
int c;
}link[3999971];
int head[3999971];
int tot;
int main()
{
int i, j, n;
int a[4111], b[4111], c[4111], d[4111];
long long ans;
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(scanf("%d", &n)!= EOF){
tot = 0;
ans = 0;
for (i = 0;i < n;i ++)
scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
memset(head, -1, sizeof(head));
for (i = 0;i < n;++ i){
for (j = 0;j < n;++ j){
insert_hash(a[i] + b[j]);
}
}
for (i = 0;i < n;++ i){
for (j = 0;j < n;++ j){
ans += find_hash(-c[i]-d[j]);
}
}
printf("%lld\n", ans);
}
return 0;
}
void insert_hash(int s){
int pos = hash_i(s);
int i;
for (i = head[pos];i != -1; i = link[i].next){
if (link[i].val == s){
link[i].c ++;
return;
}
}
link[tot].val = s;
link[tot].c = 1;
link[tot].next = head[pos];
head[pos] = tot ++;
}
int find_hash(int s){
int pos = hash_i(s);
int i;
for (i = head[pos];i != -1; i = link[i].next){
if (link[i].val == s){
return link[i].c;
}
}
return 0;
}
int hash_i(int s){
return (s + 3899971) % 3999971;
}