標籤:
描述
http://poj.org/problem?id=2503
給出一個字典,求翻譯,翻譯不了輸出eh.
分析
網上看到map可直接做,但我就是想打打Trie模板...
p.s.據說雜湊也能做,但我完全不知道那是啥...
Trie做法:在每個單詞節點存下對應翻譯的字串.
#include <cstdio>#include <iostream>#include <cstring>using namespace std;const int type=26;struct Trie{ struct node{ node* next[type]; bool v; char word[15]; node(){ v=false; for(int i=0;i<type;i++) next[i]=NULL; for(int i=0;i<15;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[25],a[15],b[15]; while(cin.getline(c,25)){ if(c[0]==‘\0‘) break; sscanf(c,"%s %s",a,b); tree.insert(a,b); } while(cin.getline(c,25)){ if(c[0]==‘\0‘) break; tree.query(c); } return 0;}Trie
#include <iostream>#include <cstdio>#include <string>#include <map>using namespace std;char c[25],a[15],b[15];map <string,string> m;int main(){ while(cin.getline(c,25)){ if(c[0]==‘\0‘) break; sscanf(c,"%s %s",a,b); m[b]=a; } map <string,string> :: iterator it; while(cin.getline(c,25)){ if(c[0]==‘\0‘) break; it=m.find(c); if(it!=m.end()){ printf("%s\n",it->second.c_str()); } else{ printf("eh\n"); } } return 0;}map
POJ_2503_Babelfish(Trie/map)