标签:
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; }
#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; }
标签:
原文地址:http://www.cnblogs.com/Sunnie69/p/5490241.html