AC自动机

HDOJ 2222

 

Problem Description

In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.
Input:
First line will contain one integer means how many cases will follow by.
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.
 

Output
Print how many keywords are contained in the description.
 

Sample Input1
5
she
he
say
shr
her
yasherhs
 

Sample Output
 3

#include #include struct node{ int mark; node* fail; node* next[26]; node(){ memset(next,NULL,sizeof(next)); fail=NULL; mark=0; } }; node* root; node* q[500010]; int n,m,cnt; char word[51],article[1000010]; void insert(char s[])//构建TIRE树 { int i=0,idx; node *p=root; while(s[i]){ idx=s[i++]-'a'; if(p->next[idx]==NULL) p->next[idx]=new node(); p=p->next[idx]; } p->mark++; } void buildautomachine()//BFS寻找失败指针,构建AC自动机 { int head=0,tail=1; q[0]=root; node* p;node* temp; while(head!=tail){ p=q[head++]; if(p==root){ for(int i=0;i<26;i++)if(p->next[i]!=NULL){ q[tail++]=p->next[i]; p->next[i]->fail=root; } continue; } for(int i=0;i<26;i++)if(p->next[i]!=NULL){ q[tail++]=p->next[i]; temp=p->fail; while(temp!=root&&temp->next[i]==NULL) temp=temp->fail; if(temp->next[i]==NULL)p->next[i]->fail=root; else p->next[i]->fail=temp->next[i]; } } } void count(char s[])//寻找匹配单词个数 { node *p;node *temp; int i=0,idx; p=root; while(s[i]){ idx=s[i++]-'a'; while(p!=root&&p->next[idx]==NULL) p=p->fail; if(p->next[idx]!=NULL)p=p->next[idx]; temp=p; while(temp!=root&&temp->mark!=-1){ cnt+=temp->mark; temp->mark=-1; temp=temp->fail; } } } int main() { scanf("%d",&n); while(n--){ cnt=0;root=new node(); scanf("%d",&m); while(m--){ scanf("%s",word); insert(word); } buildautomachine(); scanf("%s",article); count(article); printf("%d/n",cnt); } return 0; }

你可能感兴趣的:(AC自动机)