3AABBCCooxxCC%dAAAoen....END
AA: 2CC: 1
源代码:
#include<iostream> #include<algorithm> #include<string.h> using namespace std; const int KIND=26; const int MAXLEN=2000005; const int MAX=1005; int n,ans,cnt[MAX]; char word[MAX][55],str[MAXLEN]; struct TrieNode { int num; TrieNode *fail; TrieNode *next[KIND]; TrieNode() { num=0; fail=NULL; memset(next,0,sizeof(next)); } }; TrieNode *q[500005];//队列 void InsertTrieNode(TrieNode *pRoot,char s[],int number) { TrieNode *p=pRoot; int i=0; while(s[i]) { int k=s[i]-'A'; if(p->next[k]==NULL) p->next[k]=new TrieNode(); i++; p=p->next[k]; } p->num=number; } void Build_AC_automation(TrieNode *pRoot) { int head=0,tail=0,i; TrieNode *p; pRoot->fail=NULL; q[tail++]=pRoot; while(head!=tail) { p=q[head++]; for(i=0;i<KIND;i++) if(p->next[i]!=NULL) { if(p==pRoot) p->next[i]->fail=pRoot; TrieNode *tmp=p->fail; while(tmp!=NULL && tmp->next[i]==NULL) tmp=tmp->fail; if(tmp==NULL) p->next[i]->fail=pRoot; else p->next[i]->fail=tmp->next[i]; q[tail++]=p->next[i]; } } } void Search(TrieNode *pRoot,char s[]) { int i,res=0; memset(cnt,0,sizeof(cnt)); TrieNode *p,*tmp; p=pRoot; i=0; while(s[i]) { if(s[i]>='A' && s[i]<='Z') { int k=s[i++]-'A'; while(p->next[k]==NULL && p!=pRoot) p=p->fail; p=p->next[k]; if(p==NULL) p=pRoot; tmp=p; while(tmp!=pRoot)// { if(tmp->num>0) { cnt[tmp->num]++; } tmp=tmp->fail; } } else //碰到不是大写字母的,p返回到根 { i++; p=pRoot; } } for(i=1;i<=n;i++) if(cnt[i]!=0) printf("%s: %d\n",word[i],cnt[i]); } int main() { int i; TrieNode *pRoot=new TrieNode(); while(scanf("%d",&n)!=EOF) { memset(pRoot->next,NULL,sizeof(pRoot->next)); getchar(); for(i=1;i<=n;i++) { gets(word[i]); InsertTrieNode(pRoot,word[i],i); } Build_AC_automation(pRoot); gets(str); Search(pRoot,str); } system("pause"); return 0; }