20 ad ae af ag ah ai aj ak al ads add ade adf adg adh adi adj adk adl aes 5 b a d ad s
0 20 11 11 2
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int MAX = 26; struct trie{ int point; //计数 int first; //标记判断是否是同一个单词 trie *next[MAX]; }; trie *root=new trie; int p,n; char s[MAX]; void createTrie(char *s,int pose){ trie *p, *q; int len=strlen(s),pos; for(int i=0;i<len;i++){ p=root; for(int j=i;j<len;j++){ pos=s[j]-'a'; if(p->next[pos]==NULL){ q=new trie; q->point=1; q->first=pose; for(int k=0;k<MAX;k++) q->next[k]=NULL; p->next[pos]=q; p=p->next[pos]; } else if(p->next[pos]->first==pose){ p=p->next[pos]; } else{ p->next[pos]->point++; p->next[pos]->first=pose; p=p->next[pos]; } } } } int findTrie(char *s){ trie *p=root; int len=strlen(s),pos; for(int i=0;i<len;i++){ pos=s[i]-'a'; if(p->next[pos]==NULL) return 0; p=p->next[pos]; } return p->point; } void delTrie(trie *Root){ for(int i;i<MAX;i++){ if(Root->next[i]!=NULL) delTrie(Root->next[i]); } free(Root); } int main(){ for(int i=0;i<MAX;i++) root->next[i]=NULL; scanf("%d",&p); for(int i=1;i<=p;i++){ scanf("%s",s); createTrie(s,i); } scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%s",s); printf("%d\n",findTrie(s)); } delTrie(root); return 0; }
原文:http://blog.csdn.net/jhgkjhg_ugtdk77/article/details/44626903