HDU 1251-统计难题
来源:互联网 发布:muse软件怎么玩 编辑:程序博客网 时间:2024/06/09 17:14
统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)Total Submission(s): 46322 Accepted Submission(s): 16461
题目链接:点击打开链接
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
分析:
好像之前写过本题,但是最近在练字典树的题,所以接下来会给大家展示两种方法,第一种是简单的 map 映射来写的,第二种是字典树来做的,如果有想学习字典树的宝宝,看我字典树的第一篇博客点击打开链接,那个写的比较详细,本题也是根据那题的模板改动的,因为都需要标记节点的访问次数。
代码一:map映射写的
#include <iostream>#include<stdio.h>#include<string>#include<string.h>#include<map>using namespace std;int main(){ map<string,int> q; char s[15]; while(gets(s)) /**这里特别要强调一点就是接下来我的判断是以字符串的长度来判断是否是空行, 所以输入的时候不能用scanf,因为scanf以换行符结束,不会读入换行符,它会等待 你下一个字符串的输入,所以如果这里用哪个scanf,你将跳不出这个循环,但是用gets, 他会读入换行符,但它不会将该字符算为字符串的长度,它以该换行符结束, 所以我们如果检测到该行的长度为0,则就表示该行是空行,将跳出**/ { if(strlen(s)==0) break; for(int i=strlen(s);i>=0;i--)///分解该字符串,将它所有的前缀都遍历一遍,包括自身 { s[i]='\0'; q[s]++; } } while(~scanf("%s",s)) { printf("%d\n",q[s]);///直接输出该字符对应的数值即可 } return 0;}
代码二:字典树写的
#include<iostream>#include<stdio.h>#include <stdlib.h>#include<string>#include<string.h>using namespace std;char s[1005];const int INF=26;typedef struct Node{ int sum;///存该节点被访问的次数 struct Node *son[INF];///该节点的孩子}Tree;void Insert(Tree *root,char s[])///插入字符串,建树{ Tree *p=root; int k=0; char c1=s[k]; while(c1!='\0') { if(p->son[c1-'a']==NULL) { Tree *temp=new Tree; for(int i=0;i<INF;i++) temp->son[i]=NULL; temp->sum=1; p->son[c1-'a']=temp; p=p->son[c1-'a']; } else { p->son[c1-'a']->sum++; p=p->son[c1-'a']; } c1=s[++k]; }}void Find(Tree *root,char s[])///查找该字符串出现的次数{ int i=0; char c1=s[i]; Tree *p=root; while(p!=NULL&&c1!='\0') { p=p->son[c1-'a']; c1=s[++i]; } if(p==NULL) printf("0\n"); else printf("%d\n",p->sum);}void Free(Tree *root){ for(int i=0;i<INF;i++) { if(root->son[i]!=NULL) Free(root->son[i]); } free(root);}int main(){ Tree *root=new Tree; for(int i=0;i<INF;i++) root->son[i]=NULL; while(gets(s)) { if(strlen(s)==0) break; Insert(root,s); } while(~scanf("%s",s)) { Find(root,s); } Free(root); 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 1251统计难题
- HDU 1251 统计难题
- hdu 1251 统计难题
- jquery之UI型插件
- 中国银联Applepay客户端接入
- 2017 Q3 ,互联网人的薪资发生了哪些变化?
- 4.1 编程语言的几个发展阶段
- 使用ifstream和getline读取文件内容[c++]
- HDU 1251-统计难题
- 云监控服务的应用场景及概览
- css reset
- 四个字: 整 ~借 ~学 ~变
- 几个常用的算法学习网站
- CENTOS6.5 编译安装 LNMP
- 存储器(六)
- 从软件外包到阿里技术专家再到CTO,他究竟是如何一路晋升?
- mvp二级购物车的实现