字符串的hash

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值