是一道字典树的简单应用,群里面组织的专题练习,又做了一遍,比较简单,属于字典树的入门题。。。。。。。。题目:
banana band bee absolute acm ba b band abc
2 3 1 0
#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; }