• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
mengxm
博客园    首页    新随笔    联系   管理    订阅  订阅

hdu1251

http://acm.hdu.edu.cn/showproblem.php?pid=1251

今天刚看了字典树的资料,想做题练练手,结果很悲剧,字典树调了4个小时才做出一道水题

此题题意就是求解单词前缀的数量,通过字典树减少内存,并且查找单词时间只与单词长度有关

对于此题主要有一点提示就是,题目明确表示输入不会有相同单词,就是说查找单个字母若已存在字典树中只需将它的前缀数+1即可,而不存在的话就是新开一个节点,前缀数为1

1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4  struct node
5 {
6 node*next[26];
7 int num;
8 }*root;
9 int bulid(char str[],int k,node*tmproot)
10 {
11 do
12 {
13 if(tmproot->next[str[k]-'a']==NULL)
14 {
15 node*p=(node*)malloc(sizeof(node));
16 tmproot->next[str[k]-'a']=p;
17 for(int i=0;i<26;i++)
18 tmproot->next[str[k]-'a']->next[i]=NULL;
19 tmproot->next[str[k]-'a']->num=1;
20 tmproot=tmproot->next[str[k]-'a'];
21 }
22 else
23 {
24 tmproot->next[str[k]-'a']->num+=1;
25 tmproot=tmproot->next[str[k]-'a'];
26 }
27 }while(++k<strlen(str)); //构建字典树,并存储前缀编码数
28 }
29 int visit(char str_visit[],int k,node*tmproot)
30 {
31 while(k<strlen(str_visit))
32 if(tmproot->next[str_visit[k]-'a']!=NULL)
33 tmproot=tmproot->next[str_visit[k++]-'a'];
34 else return 0;
35 return tmproot->num; //在遍历字符过程中如果字符不存在则返回0,存在返回最后一个字符的前缀编码值
36 }
37 int main()
38 {
39 char str[20];
40 root=(node*)malloc(sizeof(node));
41 for(int i=0;i<26;i++) root->next[i]=NULL;
42 while(gets(str)&&str[0]!='\0')
43 {
44 bulid(str,0,root);
45 memset(str,'\0',sizeof(str));
46 }
47 while(scanf("%s",str)!=EOF)
48 printf("%d\n",visit(str,0,root));
49 return 0;
50 }
posted @ 2011-06-11 13:36  mengxm  阅读(566)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3