一道字典树的简单题,,不过对于我这种刚学字典树的菜鸟来说,还是纠结了很长时间,,,可以留下来做个模板,,,,题目:
banana band bee absolute acm ba b band abc
2 3 1 0
#include <iostream> #include <cstdio> #include <string.h> #include <malloc.h> using namespace std; struct Tire { int count; struct 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[]) { //printf("%s\n",ch); int length=strlen(ch); //printf("%d\n",length); Tire *head=a; int i,j,k; for(i=0;i<length;++i) { k=(int)(ch[i]-97); //printf("%d\n",k); 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(j=0;j<26;++j) head->tire[j]=NULL; } } } int find(char chh[]){ int llen=strlen(chh); //printf("%d\n",llen); Tire *newhead=a; int i,j,k; for(i=0;i<llen;++i){ k=(int)(chh[i]-97); if(newhead->tire[k]!=NULL) newhead=newhead->tire[k]; else {return 0;} } return newhead->count; } int main() { char s[10],ss[10]; init(); int len,num=0; while(gets(s)) { len=strlen(s); //printf("%d\n",len); if(len==0) break; //printf("uuuuu\n"); insert(s); //printf(".....\n"); } while(gets(ss)) { num=0; num=find(ss); printf("%d\n",num); } }