http://acm.hdu.edu.cn/showproblem.php?pid=1251
banana band bee absolute acm ba b band abc
2 3 1 0
/** hdu 1251 Tire树(字典树)的应用 解题思路:构造字典树,查询公共前缀的个数,算是个模板吧 */ #include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> using namespace std; struct node { int count; node *childs[26]; node() { count=0; for(int i=0;i<26;i++) { childs[i]=NULL; } } }; node *root=new node; node *current,*newnode; void insert(char *str) { current=root; int len=strlen(str); for(int i=0;i<len;i++) { int m=str[i]-'a'; if(current->childs[m]!=NULL) { current=current->childs[m]; ++(current->count); } else { newnode=new node; ++(newnode->count); current->childs[m]=newnode; current=newnode; } } } int search(char *str) { current=root; int len=strlen(str); for(int i=0;i<len;i++) { int m=str[i]-'a'; if(current->childs[m]==NULL) return 0; current=current->childs[m]; } return current->count; } int main() { char str[20]; while(gets(str),strcmp(str,"")) { insert(str); } while(gets(str)!=NULL) { printf("%d\n",search(str)); } return 0; }