哈希-4 Values whose Sum is 0 分类: POJ 哈希 2015-08-07 09:51 3人阅读 评论(0) 收藏
4 Values whose Sum is 0
Time Limit: 15000MS Memory Limit: 228000K
Total Submissions: 17875 Accepted: 5255
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
Southwestern Europe 2005
哈希的一道比较简单的题,
题意:给你四个集合,从四个集合中分别选出一个元素,使四个元素的和为零,问有几种选法;
方法:先让两个集合加和,用哈希链表,储存计算的结果,有后两个集合的计算结果查找,不过直接写链表可能比较耗时,我交了一次11s多,后来换成前向星3s多.
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define eps 1e-9
#define LL long long
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define CRR fclose(stdin)
#define CWW fclose(stdout)
#define RR freopen("input.txt","r",stdin)
#define WW freopen("output.txt","w",stdout)
const int MAX = 4010;
const int Mod = 10000007;
struct node
{
int num;
int data;
int next;
} H[Mod*10];
int head[Mod];
int a[MAX],b[MAX],c[MAX],d[MAX];
int top;
int Creat(int ans)
{
H[top].num=1;
H[top].data=ans;
return top++;
}
int main()
{
int n;
int ans;
int p,q;
int Max;
while(~scanf("%d",&n))
{
memset(head,-1,sizeof(head));
for(int i=0; i<n; i++)
{
scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);
}
top=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
ans=a[i]+b[j];
p=abs(ans)%Mod;
q=head[p];
while(q!=-1)
{
if(H[q].data==ans)
{
H[q].num++;
break;
}
q=H[q].next;
}
if(q==-1)
{
q=Creat(ans);
H[q].next=head[p];
head[p]=q;
}
}
}
Max=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
ans=-1*(c[i]+d[j]);
p=abs(ans)%Mod;
q=head[p];
while(q!=-1)
{
if(H[q].data==ans)
{
Max+=H[q].num;
break;
}
q=H[q].next;
}
}
}
printf("%d\n",Max);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。