1. 程式人生 > >【HASH】 POJ

【HASH】 POJ

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

Hint

Huge input and output,scanf and printf are recommended.

主要是輸入很噁心

給你a,b兩個單詞,b對應a

之後給你b,讓你輸出a,如果沒有就是eh

因為輸入的限制不能直接用map<string,string>

只能用hash的方法把a存下來,把b變成一個hash值map[b]=cas

然後查詢的時候算出hash值,找到map中對應的值,也就是第幾個,輸出答案即可

這裡的base用31,因為輸入的都是小寫字母,所以用31,13就錯了

#include <iostream>
#include <map>
#include <cstdio>
#include <cstring>
#include <string.h>
using namespace std;
const int maxn=1e5+7;
const int base=31;
map <int,int> mp;
char q[25];
char s[maxn][25];
char str[105];
int tot[maxn];
int main()
{
    int cas=0;
    while(1)
    {
        gets(str);
        int len=strlen(str);
        if(str[0]==NULL) break;
        cas++;
        int num1=0,num2=0;
        int flag=0;
        for(int i=0;i<len;i++)
        {
            if(str[i]==' ') {flag=1;continue;}
            if(!flag)
            {
                s[cas][++num1]=str[i];
                //cout<<s[cas][num1];
            }
            else
            {
                num2=num2*base+str[i];
                //cout<<str[i]<<" ";
            }
        }

        //cout<<endl;
        mp[num2]=cas;
        tot[cas]=num1;
    }

    while(~scanf("%s",q))
    {
        int len=strlen(q);
        int num=0;
        for(int i=0;i<len;i++)
        {
            num=num*base+q[i];
            //cout<<q[i]<<" ";
        }
        //cout<<endl;
        int k=mp[num];
        for(int i=1;i<=tot[k];i++)
        {
            cout<<s[k][i];
        }
        if(!mp[num]) cout<<"eh";
        cout<<endl;
    }
    return 0;
}