uva10282 - Babelfish(字典)

来源:互联网 发布:linux下好用的输入法 编辑:程序博客网 时间:2024/05/17 04:32

哈希查找

题意简单,思路简单,就是被0坑了一次。

代码如下:

#include <cstdio>#include <cstring>#define M 100013struct node{    char dic[20], eng[20];};int head[M], next[M];node st[M];char now_str[20];int hash(char *A){    int ans = 0, len = strlen(A);    for(int i = 0; i < len; i++)    ans = (ans * 26 + A[i]-'a')%M;    return ans;}int try_to_insert(int cur){    int h = hash(st[cur].dic), u = head[h];    while(u)    {        if(strcmp(st[u].dic,st[cur].dic)==0) return 1;        u = next[u];    }    next[cur] = head[h];    head[h] = cur;    return 0;}int is_find(){    int h = hash(now_str), u = head[h];    while(u)    {        if(strcmp(st[u].dic,now_str)==0) return u;        u = next[u];    }    return 0;}int main (){    int t;    memset(head,0,sizeof(head));    memset(next,0,sizeof(next));    for(int i = 1;; i++)    {        if((st[i].eng[0]=getchar())=='\n') break;        scanf("%s",st[i].eng+1);    getchar();        scanf("%s",st[i].dic);  getchar();        try_to_insert(i);    }    while(scanf("%s",now_str)!=EOF)    {        getchar();        if((t=is_find())!=0) printf("%s\n",st[t].eng);        else printf("eh\n");    }    return 0;}