Hdu1251 - 统计难题 - 字典树

来源:互联网 发布:曲面软件 编辑:程序博客网 时间:2024/06/05 00:09
#include<stdio.h>#include<string.h>struct tree{int count;tree *next[30];tree(){count=0;for(int i=0;i<26;i++){next[i]=NULL;}}}*root;void build(char *word){tree *item=root;for(int i=0;word[i]!=NULL;i++){int j=word[i]-'a';if(item->next[j]==NULL){item->next[j]=new tree;}item=item->next[j];item->count++;}}int find(char *word){tree *item=root;for(int i=0;word[i]!=NULL;i++){int j=word[i]-'a';if(item->next[j]==NULL){return 0;}item=item->next[j];}return item->count;}int main(){root=new tree;char word[30];while(gets(word)!=NULL){if(strlen(word)==0){break;}build(word);}while(gets(word)!=NULL){printf("%d\n",find(word));}}

0 0
原创粉丝点击