UVA - 10282 Babelfish (字符串hash)

字符串hash模板题
字符串hash模板

int get_hash(char *s)
{
    int seed=131;//可以用其他代替
    int hash=0;
    for(int i=0;s[i]!='\0';i++)
    {
        hash=hash*seed+(s[i]-'a');
    }
    return (hash & 0x7FFFFFFF)%mod; //mod取最大素数
}

AC代码:

#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
#define mod 100003
char flag[100007][50];
char aim[100007][50];
int next1[100007];
int first[100007];
int get_hash(char *s)
{
    int seed=131;
    int hash=0;
    for(int i=0;s[i]!='\0';i++)
    {
        hash=hash*seed+(s[i]-'a');
    }
    return (hash & 0x7FFFFFFF)%mod;
}
void add_hash(int s)
{
    int h=get_hash(aim[s]);
    next1[s]=first[h];
    first[h]=s;
}
int main()
{
    char a[101];
    int t=0;
    memset(next1,-1,sizeof(next1));
    memset(first,-1,sizeof(first));
    while(gets(a)&&a[0]!='\0')
    {
        int i;
        for(i=0;a[i]!=' ';i++)
        {
            flag[t][i]=a[i];
        }
        flag[t][i]='\0';
        int tt=0;
        i++;
        while(a[i]!='\0')
        {
            aim[t][tt++]=a[i++];
        }
        aim[t][tt]='\0';
        add_hash(t);
        t++;
    }
    char st[101];
    while(gets(st))
    {
        int h=get_hash(st);
        h=first[h];
        int flog=0;
        while(h!=-1)
        {
            if(strcmp(aim[h],st)==0)
            {
                printf("%s\n",flag[h]);
                flog=1;
                break;
            }
            h=next1[h];
        }
        if(!flog)
        printf("eh\n");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值