hdu 1800
题意:找相等的数字的个数最多的那个,把个数输出。注意前缀零。
这题用trie做过了,也可用hash做。
把数字作为字符串读入,用字符串hash函数把字符串哈希成一个数值插到哈希表中,用count计算相等的个数就行,so easy~
这里我们用到的字符串函数是ELFhash
inline int ELFhash(char *key)
{
unsigned long h=0;
unsigned long g;
while(*key)
{
h=(h<<4)+*key++;
g=h&0xf0000000L;
if(g)
h^=g>>24;
h&=~g;
}
return h;
}
一般字符串的都用这个函数,这个函数的功能是把某个字符串哈希成一个数值。
这题的代码:
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <memory.h>
using namespace std;
/*
*
*/
#define maxn 7003
int hash[maxn],count[maxn],n;
int maxit;
inline int ELFhash(char *key)
{
unsigned long h=0;
unsigned long g;
while(*key)
{
h=(h<<4)+*key++;
g=h&0xf0000000L;
if(g)
h^=g>>24;
h&=~g;
}
return h;
}
inline void hashit(char *s)
{
int k;
while(*s=='0')//注意前缀零
s++;
k=ELFhash(s);//k就是字符串对应的hash值
int t=k%maxn;
while(hash[t]!=k&&hash[t]!=-1)
t=(t+10)%maxn;//用开放地址法解决冲突
if(hash[t]==-1)//找到一个开放地址就插入
count[t]=1,hash[t]=k;
else if(++count[t]>maxit)//找到给定的关键字,就吧count值加1,并判断是不是最大的
maxit=count[t];
return ;
}
int main(int argc, char** argv) {
char str[100];
while(scanf("%d",&n)!=EOF)
{
memset(hash,-1,sizeof(hash));
getchar();
maxit=1;
for(int i=0;i<n;i++)
{
gets(str);//读入每个字符串
hashit(str);//把每个字符串哈希成对应的数值
}
cout<<maxit<<endl;
}
return 0;
}