hdu---统计难题
来源:互联网 发布:日本电影翻译软件 编辑:程序博客网 时间:2024/06/18 06:50
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
bananabandbeeabsoluteacmbabbandabc
Sample Output
2310#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int MAXN = 500000;struct Trie{ int next[26];//next的话它的作用是为下一个字符作铺垫 int val;//val是随你自己设定它的作用的} tree[MAXN];int nxt;char str[MAXN];void Insert(char *s){ int rt=0, len = strlen(s); for(int i=0; i < len; i++) { int c=s[i]-'a'; if(!tree[rt].next[c]) { tree[nxt].val++; tree[rt].next[c]=nxt++; } else tree[tree[rt].next[c]].val++; rt = tree[rt].next[c]; }}int Find(char *s){ int rt=0,len=strlen(s); for(int i=0;i<len;i++) { int c = s[i]-'a'; if(!tree[rt].next[c]) return 0; rt = tree[rt].next[c]; } return tree[rt].val;}int main(){ memset(tree,0, sizeof(tree)); nxt = 1; while(gets(str)!=NULL) { int len=strlen(str); if(len==0) break; Insert(str); } while(scanf("%s",str)!=EOF) printf("%d\n",Find(str)); return 0;}我的注释理解#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int MAXN = 500000;struct Trie{ int next[26];//next的话它的作用是为下一个字符作铺垫 int val;//val是随你自己设定它的作用的} tree[MAXN];int nxt;char str[MAXN];void Insert(char *s){ int rt=0, len = strlen(s); for(int i=0; i < len; i++) { int c=s[i]-'a'; if(!tree[rt].next[c])//不存在s[0]到s[i]的前缀,也就是说这是一个新的前缀了 { tree[nxt].val++;//接着nxt,开始计算新的前缀的个数 tree[rt].next[c]=nxt++;//出现了新的前缀,nxt就得加一次 } else tree[tree[rt].next[c]].val++;//存在s[0]到s[i]的前缀,那s[0]到s[i]这个前缀加一次 rt = tree[rt].next[c];//为下个字符作准备 }}int Find(char *s){ int rt=0,len=strlen(s); for(int i=0;i<len;i++) { int c = s[i]-'a'; if(!tree[rt].next[c]) return 0; rt = tree[rt].next[c]; } return tree[rt].val;//每一个rt都对应着一种前缀的个数,并且rt等于nxt-1, //rt和nxt-1是代表同一个意思,都可以表示前缀的种类数(因为nxt是从1开始,所以要减去1)}int main(){ memset(tree,0, sizeof(tree)); nxt = 1; while(gets(str)!=NULL) { int len=strlen(str); if(len==0) break; Insert(str); } while(scanf("%s",str)!=EOF) printf("%d\n",Find(str)); return 0;}
0 0
- HDU 1251 统计难题
- HDU 1251 统计难题
- hdu 1251 统计难题
- HDU 1251:统计难题
- HDU 1251 统计难题
- Hdu-1251 统计难题
- hdu 1251 统计难题
- hdu 1251 统计难题
- hdu 1251 统计难题
- HDU-1251-统计难题
- HDU 1251 统计难题
- hdu 1251统计难题
- hdu 1251统计难题
- hdu 1251 统计难题
- HDU 1251 统计难题
- hdu 统计难题
- hdu 1251统计难题
- HDU 1251 统计难题
- vue引入jquery的方法
- 机器学习笔记9——特征选择
- Nginx从入门到精通
- 文章标题
- Android仿淘宝详情页面viewPager滑动到最后一张图片跳转的功能
- hdu---统计难题
- hibernate 注解入门实例
- My97DatePicker设置文档
- ffmpeg avcodec_encode_video2 函数报错
- 查询MYSQL表字段最大值的方法
- Java中使用MongoDB详解
- iOS LaunchScreen.storyboard xib加载启动页面不显示问题
- 《MySQL运维内参》书籍目录备忘
- 关于CHM格式的帮助文档打首次开时是乱码的问题