您的位置:首页 > 产品设计 > UI/UE

uva 1152 4 values whose sum is zero ——yhx

2016-05-02 16:44 363 查看
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) 2 AB C 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 rst line of the input le 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 test case, your program has to write the number quadruplets whose sum is zero.
The outputs of two consecutive cases will be separated by a blank line.

#include<cstdio>
#include<cstring>
int abs(int x)
{
if (x>=0) return x;
return -x;
}
const int m=1098469;
int a[4010],b[4010],c[4010],d[4010],first[1100000],next[17000000],num[17000000];
int main()
{
int i,j,k,n,p,q,x,y,z,t,ans;
scanf("%d",&t);
while (t--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
memset(d,0,sizeof(d));
memset(first,0,sizeof(first));
memset(next,0,sizeof(next));
memset(num,0,sizeof(num));
ans=0;
scanf("%d",&n);
for (i=1;i<=n;i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
x=a[i]+b[j];
p=abs(x%m);
next[(i-1)*n+j]=first[p];
first[p]=(i-1)*n+j;
num[(i-1)*n+j]=x;
}
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
x=-c[i]-d[j];
p=abs(x%m);
for (k=first[p];k;k=next[k])
if (x==num[k]) ans++;
}
printf("%d\n",ans);
if (t) printf("\n");
}
}


枚举a+b,把所有值存起来,然后枚举-c-d,在a+b中查找。

具体查找方法是哈希,除k取余法即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: