比赛 20120302 评测结果 AAAAAAAAAA
题目名称 有道搜索框 最终得分 100
用户昵称 Makazeu 运行时间 0.000 s
代码语言 C++ 内存使用 0.00 MiB
提交时间 2012-03-02 18:27:22
显示代码纯文本
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #include <iostream>
  5. #define readfile(str) freopen(str,"r",stdin)
  6. #define writefile(str) freopen(str,"w",stdout)
  7. using namespace std;
  8.  
  9. const int base='a';
  10. const int SonNum=26;
  11. const int MAXN=10001;
  12. char Word[MAXN][21];
  13. class Trie
  14. {
  15. public:
  16. bool isStr;
  17. int pos;
  18. class Trie *Son[SonNum];
  19. };
  20.  
  21. Trie *Root;
  22. int Top=0;
  23. int P=0;
  24. int N,M;
  25.  
  26. Trie *NewTrie()
  27. {
  28. Trie *temp=new Trie;
  29. temp->isStr=false;
  30. temp->pos=0;
  31. for(int i=0;i<SonNum;i++)
  32. temp->Son[i]=NULL;
  33. return temp;
  34. }
  35.  
  36. void Insert(Trie *pnt,char *s,int len)
  37. {
  38. Trie *temp=pnt;
  39. for(int i=0;i<len;i++)
  40. {
  41. if(temp->Son[s[i]-base]==NULL)
  42. temp->Son[s[i]-base]=NewTrie();
  43. temp=temp->Son[s[i]-base];
  44. }
  45. temp->isStr=true;
  46. temp->pos=Top;
  47. }
  48.  
  49. void dfs(Trie *pnt)
  50. {
  51. Trie *temp=pnt;
  52. if(temp->isStr)
  53. {
  54. if(P==0)
  55. printf("%s",Word[temp->pos]);
  56. else
  57. printf(" %s",Word[temp->pos]);
  58. P++;
  59. }
  60. if(P==8)
  61. return;
  62. for(int i=0;i<SonNum;i++)
  63. {
  64. if(P==8)
  65. return;
  66. if(temp->Son[i]!=NULL)
  67. dfs(temp->Son[i]);
  68. }
  69. }
  70.  
  71. void Search(Trie *pnt,char *s,int len)
  72. {
  73. Trie *temp=pnt;
  74. for(int i=0;i<len;i++)
  75. {
  76. if(temp->Son[s[i]-base]==NULL)
  77. {
  78. printf("%s",s);
  79. return;
  80. }
  81. temp=temp->Son[s[i]-base];
  82. }
  83. P=0;
  84. dfs(temp);
  85. }
  86.  
  87. bool check(Trie *pnt,char *s,int len)
  88. {
  89. Trie *temp=pnt;
  90. for (int i=0;i<len;i++)
  91. {
  92. if(temp->Son[s[i]-base]==NULL)
  93. return false;
  94. temp=temp->Son[s[i]-base];
  95. }
  96. return temp->isStr;
  97. }
  98.  
  99. void init()
  100. {
  101. Root=NewTrie();
  102. char str[20];
  103. int len;
  104. scanf("%d\n",&N);
  105. for(int i=1;i<=N;i++)
  106. {
  107. memset(str,'\0',sizeof(str));
  108. scanf("%s\n",str);
  109. len=strlen(str);
  110. if(check(Root,str,len))
  111. continue;
  112. Top++;
  113. for(int i=0;i<len;i++)
  114. Word[Top][i]=str[i];
  115. Insert(Root,str,len);
  116. }
  117. scanf("%d\n",&M);
  118. for(int i=1;i<=M;i++)
  119. {
  120. memset(str,'\0',sizeof(str));
  121. scanf("%s\n",str);
  122. Search(Root,str,strlen(str));
  123. if(i!=M)
  124. printf("\n");
  125. }
  126. }
  127.  
  128. int main()
  129. {
  130. readfile("youdao.in"),writefile("youdao.out");
  131. init();
  132. return 0;
  133. }