hdu 1800 Flying to the Mars ——hash
今天对着课件写了一个串的hash ha是最初的hash值,t是最终存放在数组里面的hash值,就是数组下标。由于不同的串产生的ha不一样,让hash[t]=ha,就可以判断当前的串是不是和原来的那个串一样了
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define MAXN 7003
int max;
int hashtable[MAXN],count[MAXN];
unsigned int hash(char *s)
{
unsigned int seed=131;
unsigned int h=0;
while(*s=='0')
*s++;
while(*s)
h=h*seed+(*s++);
int ha=h&0x7fffffff;
int t=ha%MAXN;
while(hashtable[t]!=-1&&hashtable[t]!=ha)
{
t=(t+10)%MAXN;
}
hashtable[t]=ha;
count[t]++;
return t;
}
int main(void)
{
int n;
while(scanf("%d",&n)==1)
{
max=0;
memset(count,0,sizeof(count));
memset(hashtable,-1,sizeof(hashtable));
int i;
for(i=1;i<=n;i++)
{
char s[40];
scanf("%s",s);
int t=hash(s);
// hash[h]++;
if(count[t]>max)
max=count[t];
}
printf("%d\n",max);
}
}
浙公网安备 33010602011771号