Babelfish-哈希编码

来源:互联网 发布:电脑卡片制作软件 编辑:程序博客网 时间:2024/05/17 07:47

有一点我不太清楚为什么

    return   (sum & 0x7FFFFFFF) % MAXD;


如果改成

    return   sum% MAXD;


 

就WA了,为什么。。。

#include<cstdio>#include<cstring>#include<iostream>using namespace std;#define MAXD 100003char word[MAXD][12];char dict[MAXD][12];int head[MAXD] = {0};int next[MAXD];char t[15];int hash(char w[]){    int L = strlen(w);    int sum = 0;    for(int i = 0;i < L;i++)        sum =  10 * sum + w[i];    return   (sum & 0x7FFFFFFF) % MAXD;}int add(int n){    int  x = hash(dict[n]);    next[n] = head[x];    head[x] = n;    return 1;}int search_word(){    int  x = hash(t);    int  u = head[x];    while(u){        if(strcmp(dict[u],t)==0) return u;        u = next[u];    }    return -1;}int main(){    int N = 1;    char str[30];    while (gets(str)){        if(str[0]=='\0')            break;        int i;        for(i = 0; str[i] != ' '; ++i)            word[N][i] = str[i];        word[N][i] = '\0';        char *p = str + i + 1;        i = 0;        while (*p)            dict[N][i++] = *p++;        dict[N][i] = '\0';        add(N);        ++N;    }    while (gets(t)) {        int index = search_word();        if (index == -1)            puts("eh");        else            printf("%s\n", word[index]);    }    return 0;}


 去查看了一下关于字符串的哈希函数
http://www.cnblogs.com/uvsjoh/archive/2012/03/27/2420120.html

unsigned int BKDRHash(char *str)
{
unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
unsigned int hash = 0;

while (*str)
{
hash = hash * seed + (*str++);
}

return (hash & 0x7FFFFFFF);
}

0 0
原创粉丝点击