首页 > 代码库 > POJ2503(hash)

POJ2503(hash)

Babelfish

Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 41263 Accepted: 17561

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 ogdaycat atcaypig igpayfroot ootfrayloops oopslayatcayittenkayoopslay

Sample Output

catehloops

Hint

Huge input and output,scanf and printf are recommended.
 
思路:把字符串哈希成26进制数,然后查找的复杂度就是线性的。字符串共有26^10种可能,约等于10^14,可以用long long存下。使用map,key为哈希值,value为该串的位置。
 1 //2016.9.4 2 #include <iostream> 3 #include <cstdio> 4 #include <cstdlib> 5 #include <cstring> 6 #include <map> 7 #define N 100005 8  9 using namespace std;10 11 char s1[N][12], s2[N][12], str[25];12 map<long long, int> Hash;13 14 long long F(char* s)//把字符串hash成一个26进制数15 {16     int len = strlen(s);17     long long h = 0;18     for(int i = 0; i < len; i++)19         h = h*26+(s[i]-a);20     return h;21 }22 23 int main()24 {25     int cnt = 0;26     while(gets(str))27     {28         if(str[0] == \0)break;29         sscanf(str,"%s%s", s1[cnt], s2[cnt]);30         long long h = F(s2[cnt]);31         Hash[h] = cnt;32         cnt++;33     }34     while(gets(str))35     {36         if(str[0] == \0)break;37         long long h = F(str);38         if(Hash.find(h)!=Hash.end())//map按key查找,失败返回end39         printf("%s\n", s1[Hash[h]]);40         else printf("eh\n");41     }42 43     return 0;44 }

 

POJ2503(hash)