思路:就是用一个字典树翻译单词的问题,我们用题目中给出的看不懂的那些单词建树,这样到每个单词的叶子结点中存放原来对应的单词就好。
这样查询到某个单词时输出叶子结点存的就行,查不到就"en"呗。这题用hash也是可以的
1 1 #include<iostream> 2 2 #include<cstdio> 3 3 #include<stdio.h> 4 4 #include<cstring> 5 5 #include<cmath> 6 6 #include<vector> 7 7 #include<stack> 8 8 #include<map> 9 9 #include<set> 1010 #include<list> 1111 #include<queue> 1212 #include<string> 1313 #include<algorithm> 1414 #include<iomanip> 1515 using namespace std; 1616 1717 struct node 1818 { 1919 int cnt; 2020 char c[26];//结点所对应的字符 2121 struct node *next[26]; 2222 node () 2323 { 2424 cnt = 0; 2525 memset(next,0,sizeof(next)); 2626 } 2727 }; 2828 node * root = NULL;//根结点初始为NULL 2929 3030 void BuildTrie(char *s,char *temp) 3131 { 3232 node *p = root; 3333 node *tmp = NULL; 3434 int l = strlen(s); 3535 for(int i = 0;i < l ;i ++) 3636 { 3737 if(p->next[s[i]-'a'] == NULL) 3838 { 3939 tmp = new node; 4040 p->next[s[i]-'a'] = tmp; 4141 4242 } 4343 p = p->next[s[i]-'a']; 4444 } 4545 p->cnt = 1; 4646 strcpy(p->c,temp);//存放翻译结果 4747 4848 } 4949 5050 void Query(char *s) 5151 { 5252 node *p = root; 5353 int l = strlen(s); 5454 for(int i = 0 ;i< l ;i++) 5555 { 5656 if(p->next[s[i]-'a'] == NULL) 5757 { 5858 printf("eh\n"); 5959 return ; 6060 } 6161 p = p->next[s[i]-'a']; 6262 } 6363 printf("%s\n",p->c); 6464 return ; 6565 } 6666 6767 void Del(node * root) 6868 { 6969 for(int i = 0;i < 26;i++) 7070 { 7171 if(root->next[i]) 7272 { 7373 Del(root->next[i]); 7474 } 7575 } 7676 } 7777 7878 int main() 7979 { 8080 char str[30],s1[15],s2[15]; 8181 root = new node; 8282 while(gets(str)) 8383 { 8484 if(str[0] == '\0') 8585 break; 8686 sscanf(str,"%s %s",s1,s2); 8787 BuildTrie(s2,s1);//注意参数位置 8888 } 8989 while(scanf("%s",str)!=EOF) 9090 Query(str); 9191 return 0; 9292 }