hash Babelfish poj 2503

17779 ワード

Babelfish
Time Limit: 3000MS
 
Memory Limit: 65536K
Total Submissions: 27380
 
Accepted: 11823
Description
You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.
Input
Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.
Output
Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".
Sample Input
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

Sample Output
cat
eh
loops


  
  
  
  
2503
Accepted
5068K
235MS
C++
1376B
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

#define SIZE 199999

struct Node 
{
   char key[12], fore[12];
   bool flag;
   Node () { flag = false; }
} table[SIZE];

unsigned int BKDRHash(char *str)
{
    unsigned int seed = 131;
    unsigned int hash = 0;
    while (*str)
    {
        hash = hash * seed + (*str++);
    }
    return (hash & 0x7FFFFFFF)%SIZE;
}

void insert(char *s1, char *s2)
{
    int pos = BKDRHash(s2), m = 0;
    while (table[pos].flag)
	{
        pos += 2 * (++m) - 1;
        if (pos >= SIZE) pos -=SIZE;
    }
    strcpy(table[pos].key, s2);
    strcpy(table[pos].fore, s1);
    table[pos].flag = true;
}

int main()
{
    char buff[50], s1[20], s2[20];
    while (gets(buff) && buff[0] != '\0')
    {
        sscanf (buff, "%s %s", s1, s2);
        insert (s1, s2);
    }
    while (scanf ("%s", s1) != EOF)
	{
        int pos = BKDRHash(s1), m = 0;
        bool flag = false;

        while (table[pos].flag)
		{
            if (strcmp(table[pos].key, s1) == 0) 
			{ printf ("%s
", table[pos].fore); flag = true; break; } else { pos += 2 * (++m) - 1; pos = (pos >=SIZE ? pos -SIZE : pos); } } if (!flag) printf ("eh
"); getchar(); } return 0; }