Ignatius is so lucky that he met a Martian yesterday. But he didn't know the language the Martians use. The Martian gives him a history book of Mars and a dictionary when it leaves. Now Ignatius want to translate the history book into English. Can you help him?
START from fiwo hello difh mars riwosf earth fnnvk like fiiwj END START difh, i'm fiwo riwosf. i fiiwj fnnvk! END
hello, i'm from mars.
i like earth!
Huge input, scanf is recommended.
题目意思:给你一本火星字典,然后根据火星字典,把一句话翻译成英文,如果一个词在火星字典里找不
到就不翻译,直接写出来。
解题思路:通过字典树,将字典进行建树,然后查找,这个题的关键在于怎么把这段发翻译过来,于是想
到通过函数或者ASCII码判断是否为小写字母,判断到不是时,就将前面的字母输入到树中进行
查找,若找到就翻译,反之不翻译。这里找不到的判定标准有两个:1.遇到指针为空 2.指针不
为空但最后一个字母不是树中标记过的字母,比如树中存在asdf,而你输入的为asd,那么就是
找不到。
#include<iostream> #include<cstring> #include<algorithm> #include<ctype.h> using namespace std; char s[3100]; char s2[20]; char s1[20]; struct trie{ char v[15]; int mark; trie *next[26]; trie(){ mark=0; for(int i=0;i<26;i++) { next[i]=NULL; } } }; trie *root; void creat(trie *root,char *str,char *str1) { int len=strlen(str); trie *p=root,*q; for(int i=0;i<len;i++) { int sign=str[i]-'a'; if(p->next[sign]==NULL) { q=new trie(); p->next[sign]=q; p=p->next[sign]; } else { p=p->next[sign]; } } p->mark=-1; strcpy(p->v,str1); } bool find(trie *root,char *str,int m,int j) { trie *p=root; int i=m; for(i;i<j;i++) { int id=str[i]-'a'; p=p->next[id]; if(p==NULL) { return false; } } if(p->mark!=-1) return false; cout<<p->v; return true; } void del(trie *root) { for(int i=0;i<26;i++) { if(root->next[i]) { del(root->next[i]); } } delete(root); } int main() { char str[10]; root=new trie(); scanf("%s",str); while(scanf("%s",s1)&&strcmp(s1,"END")) { scanf("%s",s2); creat(root,s2,s1); } scanf("%s",str); gets(s); while(gets(s)&&strcmp(s,"END")!=0) { int len=strlen(s); int num=0; for(int a=0;a<len;a++) { if(s[a]>='a'&&s[a]<='z') { num++; } else { if(s[a-1]<'a'||s[a-1]>'z') { cout<<s[a]; num=0; } else { if(!find(root,s,a-num,a)) { for(int q=a-num;q<a;q++) { cout<<s[q]; } } cout<<s[a]; num=0; } } } if(!find(root,s,len-num,len)) { for(int q=len-num;q<len;q++) { cout<<s[q]; } } cout<<endl; } return 0; }