是一道字典树的简单应用,群里面组织的专题练习,又做了一遍,比较简单,属于字典树的入门题。。。。。。。。题目:
统计难题 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 7637 Accepted Submission(s): 2974
注意:本题只有一组测试数据,处理到文件结束.
#include <iostream> #include <cstdio> #include <string.h> #include <string> #include <malloc.h> using namespace std; struct Tire{ int count; Tire *tire[26]; }*a; void init(){ a=(Tire *)malloc(sizeof(Tire)); for(int i=0;i<26;++i) a->tire[i]=NULL; } void insert(char ch[]){ int len=strlen(ch); Tire *head=a; for(int i=0;i<len;++i){ int k=ch[i]-'a'; if(head->tire[k]!=NULL){ head=head->tire[k]; head->count++; } else{ head->tire[k]=new Tire; head=head->tire[k]; head->count=1; for(int j=0;j<26;++j) head->tire[j]=NULL; } } } int find(char ch[]){ int len=strlen(ch); Tire *head=a; int i,k; for(i=0;i<len;++i){ k=ch[i]-'a'; if(head->tire[k]==NULL){ return 0; } else{ head=head->tire[k]; } } return head->count; } int main(){ char s[10],ss[10]; init(); int len,num=0; while(gets(s)){ len=strlen(s); if(len==0) break; insert(s); } while(gets(ss)){ num=find(ss); printf("%d\n",num); } return 0; }