【trie树】HDU1247Hat’s Words

迷南。 2022-01-09 05:41 364阅读 0赞

ContractedBlock.gif ExpandedBlockStart.gif

  1. Hats Words
  2. Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
  3. Total Submission(s): 19500 Accepted Submission(s): 6867
  4. Problem Description
  5. A hats word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
  6. You are to find all the hats words in a dictionary.
  7. Input
  8. Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
  9. Only one case.
  10. Output
  11. Your output should contain all the hats words, one per line, in alphabetical order.
  12. Sample Input
  13. a
  14. ahat
  15. hat
  16. hatword
  17. hziee
  18. word
  19. Sample Output
  20. ahat
  21. hatword
  22. Author
  23. 戴帽子的
  24. Recommend
  25. Ignatius.L | We have carefully selected several similar problems for you: 1075 1671 1298 1800 2846

T

这道题也是比较简单的trie树的题,开始觉得很懵逼,最后才发现其实暴力就可以

对于每个单词枚举断点,然后查前后是否都存在

我们来计算下时间复杂度,假设n个单词,每个单词长度最大为m

那么插入O(nm);

查询时候O(nmm);

总复杂度O(nm+m2n);

这道题的n是50000,m假设是30,那么很明显可以过

上代码

  1. 1 #include<cstdio>
  2. 2 #include<algorithm>
  3. 3 #include<cstring>
  4. 4 #define idx(i) (i-'a')
  5. 5 #define N 50011
  6. 6 using namespace std;
  7. 7 char in[N][300];
  8. 8 int cnt=1,pp;
  9. 9 struct TRIE{
  10. int nxt[30],cnt;}tree[N*300];
  11. 10 inline int regist(){
  12. return cnt++;}
  13. 11 void insert(char *now)
  14. 12 {
  15. 13 int c,rt=0,len=strlen(now);
  16. 14 for(int i=0;i<len;i++)
  17. 15 {
  18. 16 c=idx(now[i]);
  19. 17 if(!tree[rt].nxt[c])
  20. 18 tree[rt].nxt[c]=regist();
  21. 19 rt=tree[rt].nxt[c];
  22. 20 }
  23. 21 tree[rt].cnt=1;
  24. 22 }
  25. 23 bool find(char *now,int st,int ed)
  26. 24 {
  27. 25 int rt=0;
  28. 26 for(int i=st-1;i<ed;i++)
  29. 27 {
  30. 28 if(!tree[rt].nxt[idx(now[i])])return 0;
  31. 29 rt=tree[rt].nxt[idx(now[i])];
  32. 30 }
  33. 31 return tree[rt].cnt;
  34. 32 }
  35. 33 int main()
  36. 34 {
  37. 35 while(scanf("%s",in[++pp]+1)!=EOF)insert(in[pp]+1);
  38. 36 for(int i=1;i<pp;i++)
  39. 37 {
  40. 38 int len=strlen(in[i]+1);
  41. 39 for(int j=1;j<=len;j++)
  42. 40 if(find(in[i]+1,1,j)&&find(in[i]+1,j+1,len)){printf("%s\n",in[i]+1);break;}
  43. 41 }
  44. 42 return 0;
  45. 43 }

转载于:https://www.cnblogs.com/Qin-Wei-Kai/p/10224182.html

发表评论

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

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

相关阅读

    相关 HDU1247(字典)

    题意:给定一排字符串组成一个字典,求在字典中自否存在由字典中另外两个字符串组成的字符串。   include <iostream> include <st