POJ_2503_Babelfish_(Trie/map)

时间:2022-04-09 20:58:22

描述


http://poj.org/problem?id=2503

给出一个字典,求翻译,翻译不了输出eh.

Babelfish
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 39335   Accepted: 16797

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

Hint

Huge input and output,scanf and printf are recommended.

Source

分析


网上看到map可直接做,但我就是想打打Trie模板...

p.s.据说哈希也能做,但我完全不知道那是啥...

Trie做法:在每个单词节点存下对应翻译的字符串.

Trie:

 #include <cstdio>
#include <iostream>
#include <cstring>
using namespace std; const int type=;
struct Trie{
struct node{
node* next[type];
bool v;
char word[];
node(){
v=false;
for(int i=;i<type;i++) next[i]=NULL;
for(int i=;i<;i++) word[i]='\0';
}
}*root;
Trie(){ root=new node; }
void insert(char *c1,char *c2){
node *o=root;
while(*c2){
int t=*c2-'a';
if(o->next[t]==NULL) o->next[t]=new node;
o=o->next[t];
c2++;
}
o->v=true;
strcpy(o->word,c1);
}
void query(char *c){
node* o=root;
while(*c){
int t=*c-'a';
if(o->next[t]==NULL){
printf("eh\n");
return;
}
o=o->next[t];
c++;
}
if(o->v) printf("%s\n",o->word);
else printf("eh\n");
}
}tree; int main(){
char c[],a[],b[];
while(cin.getline(c,)){
if(c[]=='\0') break;
sscanf(c,"%s %s",a,b);
tree.insert(a,b);
}
while(cin.getline(c,)){
if(c[]=='\0') break;
tree.query(c);
}
return ;
} Trie

map:

 #include <iostream>
#include <cstdio>
#include <string>
#include <map>
using namespace std; char c[],a[],b[];
map <string,string> m; int main(){
while(cin.getline(c,)){
if(c[]=='\0') break;
sscanf(c,"%s %s",a,b);
m[b]=a;
}
map <string,string> :: iterator it;
while(cin.getline(c,)){
if(c[]=='\0') break;
it=m.find(c);
if(it!=m.end()){
printf("%s\n",it->second.c_str());
}
else{
printf("eh\n");
}
}
return ;
} map