HDU 1251 统计难题

举报
Linux猿 发表于 2021/08/05 00:06:41 2021/08/05
【摘要】 题目链接~~> 做题感悟:这是接触字典树的第一题,记录一下。 解题思路:见代码(因为只有一组数据,so 不用释放内存)。 代码: #include<stdio.h>#include<iostream>#include<map>#include<string>#include<string.h>#incl...

题目链接~~>

做题感悟:这是接触字典树的第一题,记录一下。

解题思路:见代码(因为只有一组数据,so 不用释放内存)。

代码:


  
  1. #include<stdio.h>
  2. #include<iostream>
  3. #include<map>
  4. #include<string>
  5. #include<string.h>
  6. #include<stdlib.h>
  7. #include<queue>
  8. #include<algorithm>
  9. using namespace std ;
  10. #define LEN sizeof(struct node)
  11. struct node
  12. {
  13. int count ;
  14. struct node *next[26] ;
  15. } ;
  16. struct node *root ;
  17. struct node *build() // 建立新节点
  18. {
  19. struct node *p ;
  20. p=(struct node*)malloc(LEN) ;
  21. for(int i=0 ;i<26 ; i++)
  22. {
  23. p->next[i]=NULL ;
  24. }
  25. p->count=1 ;
  26. return p ;
  27. }
  28. void save(char *s) // 保存节点
  29. {
  30. struct node *p ;
  31. int len=strlen(s) ;
  32. if(!len) return ;
  33. p=root ;
  34. for(int i=0 ;i<len ;i++)
  35. {
  36. int temp=s[i]-'a' ;
  37. if(p->next[temp]!=NULL)
  38. {
  39. p=p->next[temp] ;
  40. p->count=p->count+1 ; // 存入字符便记录一下
  41. }
  42. else
  43. {
  44. p->next[temp]=build() ;
  45. p=p->next[temp] ; // 用此地址继续存
  46. }
  47. }
  48. }
  49. int seach(char *s) // 查询
  50. {
  51. int len=strlen(s) ;
  52. if(!len) return 0 ;
  53. struct node *p ;
  54. p=root ;
  55. for(int i=0 ;i<len ;i++)
  56. {
  57. int temp=s[i]-'a' ;
  58. if(p->next[temp]!=NULL)
  59. p=p->next[temp] ;
  60. else return 0 ;
  61. }
  62. return p->count ;
  63. }
  64. int main()
  65. {
  66. int ans ;
  67. char s[15] ;
  68. root=build() ;
  69. while(gets(s)&&s[0]!='\0')
  70. save(s) ;
  71. while(~scanf("%s",s))
  72. {
  73. ans=seach(s) ;
  74. printf("%d\n",ans) ;
  75. }
  76. return 0 ;
  77. }

关于字典树的博客~>
 

文章来源: blog.csdn.net,作者:Linux猿,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/nyist_zxp/article/details/19111061

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。