POJ 2503——Babelfish

骑猪看日落 2022-08-10 16:56 213阅读 0赞

这一题也没什么思路很直接,直接用字典树存储信息,在进行查找:

优点:思路直接,速度较快 缺点:占用内存较大,建立的关系是单向的,代码较长

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <cstdlib>
  4. #include <iostream>
  5. using namespace std;
  6. struct Trie
  7. {
  8. Trie *next[26];
  9. int sign;
  10. char eng[30];
  11. };
  12. Trie root;
  13. void initial(Trie *t)
  14. {
  15. for(int i=0;i<26;i++)
  16. t->next[i]=NULL;
  17. }
  18. void creatTrie(char *s1,char *s2)
  19. {
  20. Trie *p=&root,*q;
  21. int len=strlen(s1),i;
  22. for( i=0;i<len;i++)
  23. {
  24. int id=s1[i]-'a';
  25. if(p->next[id]==NULL)
  26. {
  27. q=new Trie;
  28. initial(q);
  29. q->sign=0;
  30. p->next[id]=q;
  31. p=q;
  32. }
  33. else p=p->next[id];
  34. }
  35. p->sign=1;
  36. strcpy(p->eng,s2);
  37. }
  38. string search(char *s)
  39. {
  40. Trie *p=&root;
  41. int len=strlen(s);
  42. for(int i=0;i<len;i++)
  43. {
  44. int id=s[i]-'a';
  45. if(p->next[id]==NULL)
  46. return "eh";
  47. else p=p->next[id];
  48. }
  49. if(p->sign==1)
  50. return p->eng;
  51. else return "eh";
  52. }
  53. int main()
  54. {
  55. char foreign[30],english[30],str[65];
  56. while(gets(str)&&str[0]!='\0')
  57. {
  58. sscanf(str,"%s %s",english,foreign);
  59. creatTrie(foreign,english);
  60. }
  61. while(scanf("%s",str)!=EOF)
  62. {
  63. cout<<search(str)<<endl;
  64. }
  65. return 0;
  66. }

方法二:map容器,将两者建立对应关系;

优点:建立的关系是双向的,较省空间,代码量非常小 缺点:查找速度较慢,查找时间复杂度为log n

  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstdio>
  4. #include <cstring>
  5. #include <string>
  6. #include <set>
  7. #include <map>
  8. using namespace std;
  9. map<string, string> Map;
  10. char str[60];
  11. char temp1[30], temp2[30];
  12. int main()
  13. {
  14. Map.clear();
  15. while(gets(str))
  16. {
  17. if(str[0] == '\0') break;
  18. sscanf(str, "%s %s", temp1, temp2);
  19. Map[temp2] = temp1;
  20. }
  21. while(gets(str))
  22. {
  23. if(Map.find(str) != Map.end()) cout<<Map[str]<<endl;
  24. else cout<<"eh"<<endl;
  25. }
  26. return 0;
  27. }

发表评论

表情:
评论列表 (有 0 条评论,213人围观)

还没有评论,来说两句吧...

相关阅读

    相关 POJ 2503——Babelfish

    这一题也没什么思路很直接,直接用字典树存储信息,在进行查找: 优点:思路直接,速度较快      缺点:占用内存较大,建立的关系是单向的,代码较长 include