一、问题描述
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.
二、解题思路
使用trie树。
三、代码
#include<iostream> using namespace std; struct trieNode { int next[26]; char word[12]; }; int N=200000; trieNode tt[200000]; int len; void insert(char * fw,char * tar) { trieNode * p= &tt[0]; int id ; while(*tar) { id=*tar-'a'; if(p->next[id]==-1) { p->next[id]=len; len++; } p=&tt[p->next[id]]; tar++; } strcpy(p->word,fw); } char * search(char *tar) { trieNode * p= &tt[0]; int id; while (* tar) { id=*tar -'a'; if(p->next[id]==-1) return NULL; p=&tt[p->next[id]]; tar++; } if(strlen(p->word) > 0) return p->word; else return NULL; }
void clear ( int n) { for(int i=0;i<n;++i) { strcpy(tt[i].word,""); memset(tt[i].next,-1,sizeof(tt[i].next)); } } int main() { char str1[12]; char str2[12]; clear(N); len=1; int i,j; char s[35]; int sl; while(gets(s)) { sl=strlen(s); if(sl==0) break; for(i=0;s[i]!=' ';++i) str1[i]=s[i]; str1[i]='\0'; for(j=0;i+j+1<sl;++j) str2[j]=s[i+j+1]; str2[j]='\0'; insert(str1,str2); } char * p; while(scanf("%s",&str1)!=EOF) { p=search(str1); if(p!=NULL) printf("%s\n",p); else printf("eh\n"); } return 0; }
|
四、使用map
#include<iostream> #include<string> #include<map> using namespace std; map<string,string> mp; string str; string e; string f; int main() { int sl; char str1[12]; char str2[12]; int i,j; char s[35]; while(gets(s)) { sl=strlen(s); if(sl==0) break; for(i=0;s[i]!=' ';++i) str1[i]=s[i]; str1[i]='\0'; for(j=0;i+j+1<sl;++j) str2[j]=s[i+j+1]; str2[j]='\0'; mp[string(str2)]=string(str1); } while(gets(s)) { string t=mp[string(s)]; if(t.size()==0) printf("eh\n"); else printf("%s\n",t.c_str()); }
return 0;
}
|
阅读(1104) | 评论(0) | 转发(0) |