hdu1251-统计难题 字典树经典例题

来源:互联网 发布:nginx fastcgi java 编辑:程序博客网 时间:2024/06/12 00:13

统计难题

 


Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀). 
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串. 

注意:本题只有一组测试数据,处理到文件结束. 
Output
对于每个提问,给出以该字符串为前缀的单词的数量. 
Sample Input
bananabandbeeabsoluteacmbabbandabc
Sample Output
2310
这是一道非常经典的字典树题目,赤裸裸的字典树。需要注意的是需要使用C++提交,G++会超
字典树专题:点击打开链接http://blog.csdn.net/wang_heng199/article/details/76448804
ac代码:
//提交代码使用C++,G++会超内存 #include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;struct node{int count;node *childs[26];node(){count=0;int i;for(i=0;i<26;i++)childs[i]=NULL;}};node *root=new node;node *current,*newnode;void insert(char *str)//插入 {int i,m;    current=root;    for(int i=0;i<strlen(str);i++)    {       m=str[i]-'a';        if(current->childs[m]==NULL)        current->childs[m]=new node;        current=current->childs[m];       (current->count)++;    }}int search(char *str)//查找 {int i,m;    current=root;for(i=0;i<strlen(str);i++){    m=str[i]-'a';if(current->childs[m]==NULL)return 0;current=current->childs[m];}return current->count;}int main(){char str[20];while(gets(str),strcmp(str,""))      insert(str);while(gets(str)!=NULL)    printf("%d\n",search(str));return 0;}

题目链接:点击打开链接http://acm.hdu.edu.cn/showproblem.php?pid=1251
原创粉丝点击