Original question:
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 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 is the message translated to English, one word per line. foreign words not in the dictionary shocould be translated as "eh ".
Sample Input
Dog ogday
Cat atcay
Pig igpay
Froot ootfray
Loops oopslay
Atcay
Ittenkay
Oopslay
Output for Sample Input
Cat
Eh
Loops
Question:
When you get to a strange place, the words in this place are different from those in English. Each English word corresponds to this local word (all of which are one-to-one and will not appear again ). Then some local words are given, and you need to output the corresponding English words.
Analysis and Summary:
English words and local words are simple mappings. When the number of questions reaches 100,000, hash is used to create a ing or directly sort the questions and then perform binary search. Even if the problem can be barely passed, the speed should be unsatisfactory.
Therefore, the best way to do this is to use a hash table to establish a ing relationship.
The speed is good. I ran into rank 2nd
[Cpp]
/*
* Ultraviolet A 10282-Babelfish
* Hash table
* Time: 0.076 s (ultraviolet)
* Author: D_Double
*/
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Define maxn100003
Using namespace std;
Typedef char Word [12];
Word english [MAXN], foreign [MAXN];
Const int HashSize = 100003;
Int N, head [HashSize], next [HashSize];
Inline void init_lookup_table (){
N = 1;
Memset (head, 0, sizeof (head ));
}
Inline int hash (char * str) {// string hash Function
Integer seed = 131;
Int hash = 0;
While (* str) hash = hash * seed + (* str ++ );
Return (hash & 0x7FFFFFFF) % HashSize;
}
Int add_hash (int s ){
Int h = hash (foreign [s]);
Int u = head [h];
While (u) u = next [u];
Next [s] = head [h];
Head [h] = s;
Return 1;
}
Int search (char * s ){
Int h = hash (s );
Int u = head [h];
While (u ){
If (strcmp (foreign [u], s) = 0) return u;
U = next [u];
}
Return-1;
}
Int main (){
Char str [25];
N = 1;
Init_lookup_table ();
While (gets (str )){
If (str [0] = '\ 0') break;
Int I;
For (I = 0; str [I]! = ''; ++ I)
English [N] [I] = str [I];
English [N] [I] = '\ 0 ';
Char * p = str + I + 1;
I = 0;
While (* p) foreign [N] [I ++] = * p ++;
Foreign [N] [I] = '\ 0 ';
Add_hash (N );
++ N;
}
// Query
While (gets (str )){
Int index = search (str );
If (index =-1) puts ("eh ");
Else printf ("% s \ n", english [index]);
}
Return 0;
}
Author: shuangde800