题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct TrieNode{ int count; struct TrieNode *next[26]; }; TrieNode *root=new TrieNode; void build(char *s){ TrieNode *head=root; int len=strlen(s); for(int i=0;i<len;i++){ if(head->next[s[i]-'a']==NULL){ head->next[s[i]-'a']=new TrieNode; head=head->next[s[i]-'a']; for(int i=0;i<26;i++) head->next[i]=NULL; head->count=1; } else{ head=head->next[s[i]-'a']; head->count++; } } } int search(char *s){ int len=strlen(s); TrieNode *head=root; for(int i=0;i<len;i++) if(head->next[s[i]-'a']==NULL) return 0; else head=head->next[s[i]-'a']; return head->count; } void Delete(TrieNode *p){ for(int i=0;i<26;i++){ if(p->next[i]!=NULL) delete(p->next[i]); } free(p); } int main(){ char s[20]; for(int i=0;i<26;i++) root->next[i]=NULL; root->count=0; while(gets(s)) { if(!strcmp(s,"")) break; build(s); } while(scanf("%s",s)!=EOF) { printf("%d\n",search(s)); } return 0; }