#include<cstdio>
#include<cstring>
char s[12];
//优化的字典树
struct node{
int cnt;
node *a[27];
node(){//初始化
cnt=0;
memset(a,NULL,sizeof(a));
}
}*h;
void bd(node *root){
node *p=root;
int i=0,id;
while(s[i]){
id=s[i]-'a';
if(p->a[id]==NULL) p->a[id]=new node();
//建立新的结构体指针
p=p->a[id];
p->cnt++;//每次经过都+1
i++;
}
}
int ask(char *s,node *p){
int l=strlen(s);
int k=0;
while(k<l){
if(p->a[s[k]-'a']==NULL ) return 0;
else p=p->a[s[k++]-'a'];
}
return p->cnt;
}
int main()
{
int i,l;
h=new node();
while(gets(s)){
if((l=strlen(s))==0) break;
bd(h);
}
while(gets(s))
printf("%d\n",ask(s,h));
return 0;
}
字符串专题:I - 统计难题(trie树 改良版)
最新推荐文章于 2024-05-29 08:00:00 发布