HDU
来源:互联网 发布:python sin函数 编辑:程序博客网 时间:2024/06/02 03:09
统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)Total Submission(s): 43076 Accepted Submission(s): 15465
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
bananabandbeeabsoluteacmbabbandabc
Sample Output
2310
字典树
#include<iostream>#include<string.h>#include<string>#include<stdio.h>#include<vector>using namespace std;int cnt = 0,k = 0,num[15];char c,s[15];struct node{ vector<node*>next; int num,val; node() { num = val = 0; next.clear(); }}*tree,*add;int find_and_insert(node *now,int x,int len,int ope)//now代表当前节点,ope代表操作,1为插入,0为查找{ if(x==len) return now->num; for(int i=0;i<now->next.size();i++) { if(now->next[i]->val!=num[x])//查找该前缀是否出现过 continue; if(ope) now->next[i]->num++;//具有该前缀的单词个数加一 return find_and_insert(now->next[i],x+1,len,ope); } if(ope) { add = new node; add->num = 1; add->val = num[x]; now->next.push_back(add); } else return 0; return find_and_insert(add,x+1,len,ope);}int main(){ tree = new node; add = new node; while((c=getchar())) { if(c=='\n') { cnt++; if(cnt==2) break; find_and_insert(tree,0,k,1); memset(num,0,sizeof num); k = 0; continue; } cnt = 0; num[k++] = c-'a'; } while(scanf("%s",s)!=EOF) { for(int i=0;i<strlen(s);i++) num[i] = s[i] - 'a'; cout<<find_and_insert(tree,0,strlen(s),0)<<endl; } return 0;}
阅读全文
0 0