hdu 1496 Equations ——hash

今天折腾了一下午博客搬家了……结果发现博客园还是很不错的……有语法高亮~~~~
水hash。。
就是那个sum*16不是太明白……
/*
Equations
algorithm:hash
date:2011-07-23 16:56:12
time:187MS
memory:7988K
language:G++
*/

#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#define MAXN 2000003
int pin[110];
int hash[MAXN];

int main(void)
{
int a,b,c,d;
int i,j,sum;
for(i=1;i<101;i++)
{
pin[i]
=i*i;
}
while(scanf("%d %d %d %d",&a,&b,&c,&d)==4)
{
sum
=0;
if((a>0 && b>0 && c>0 && d>0 )|| (a<0 && b<0 && c<0 && d<0))
{
puts(
"0");
continue;
}
memset(hash,
0,sizeof(hash));
for(i=1;i<=100;i++)
for(j=1;j<=100;j++)
{
hash[a
*pin[i]+b*pin[j]+1000000]++;
}
for(i=1;i<=100;i++)
for(j=1;j<=100;j++)
{
sum
+=hash[-(c*pin[i] + d*pin[j]) + 1000000];
}
printf(
"%d\n",sum*16);
}
}

有个大神说:两层循环最多只可能产生10000个不同的结果,开200W的数组将会浪费很多初始化的时间,所以开小数组+处理冲突会比较好
这个是他的代码:用的开放寻址……只用了31MS就过了!!
#include<stdio.h>
#include
<memory.h>

#define MAX 50021

int f[MAX],g[MAX];

int hash(int k)
{
int t=k%MAX;
if(t<0)
t
+=MAX;
while(f[t]!=0&&g[t]!=k)
t
=(t+1)%MAX;
return t;
}

int main()
{
int a,b,c,d,p,i,j,s,n,t[101];
for(i=1;i<=100;i++)
t[i]
=i*i;
while(scanf("%d%d%d%d",&a,&b,&c,&d)>0)
{
if(a>0&&b>0&&c>0&&d>0||a<0&&b<0&&c<0&&d<0)
{
printf(
"0\n");
continue;
}
memset(f,
0,sizeof(f));
n
=0;
for(i=1;i<=100;i++)
for(j=1;j<=100;j++)
{
s
=a*t[i]+b*t[j];
p
=hash(s);
g[p]
=s;
f[p]
++;
}
for(i=1;i<=100;i++)
for(j=1;j<=100;j++)
{
s
=-(c*t[i]+d*t[j]);
p
=hash(s);
n
+=f[p];
}
printf(
"%d\n",n*16);
}
}

  

  

你可能感兴趣的:(hash)