Letters比赛第六场1002 Babelfish解题报告

1002 Babelfish (POJ 2503)

解题思路:字符串的哈希,找一个比较好的hash函数就可以了,冲突时用链表的形式组织。用STL中的map等容器也可以过,不过性能差点。

 

代码如下:

#include <cstdlib>
#include <iostream>

using namespace std;

#define N 1000005
#define HASH 3999971

struct node
{
    char a[11];
    char b[11];
    int next;
};

struct node words[N];
int head[HASH];
int t = 0;

int inline hash(char * key)
{
    unsigned int h = 0;
    while (*key){
        h = (h << 4) + *key++;
        unsigned int g = h & 0xf0000000L;
        if (g) h ^= g >> 24;
        h &= ~g;
    }
    return h % HASH;
}

bool search(char s[])
{
    int key = hash(s);
    int u = head[key];

    while(u)
    {
        if(strcmp(s, words[u].b) == 0)
        {
            t = u;
            return true;
        }
        else
        {
            u = words[u].next;
        }
    }
    return false;
}

int main()
{
#ifdef MYLOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int i = 1;
    char s[30];

    memset(head, 0, sizeof(head));
    while(gets(s) && strcmp(s, "") != 0)
    {
        sscanf(s, "%s %s", words[i].a, words[i].b);
        int key = hash(words[i].b);
        words[i].next = head[key];
        head[key] = i++;
    }

    while(scanf("%s", s) != EOF)
    {
        if(search(s) == true)
        {
            printf("%s\n", words[t].a);
        }
        else
        {
            printf("eh\n");
        }
    }

    return 0;
}

 

 

posted @ 2012-04-24 22:10  LETTers  阅读(173)  评论(0编辑  收藏  举报