字符串专题:I - 统计难题(trie树 改良版)

来源:互联网 发布:js selected选中事件 编辑:程序博客网 时间:2024/06/05 05:30
#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++;//每次经过都+1i++;}}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;}