hdu2222——Keywords Search//AC 自动机

来源:互联网 发布:淘宝斯沃琪旗舰店 编辑:程序博客网 时间:2024/06/05 16:01

注意点:cnt 应设为0,可能一个字母对应有几个单词,所以,每次遇到时,要cnt++。计算的时候,也需count+=cnt;

#include<iostream>#include<string.h>#include<stdlib.h>using namespace std;class node {public:int cnt;node * next[26];node * fail;node(){fail =NULL;cnt =0;memset(next,NULL,sizeof(next));}};node * tire;node *que[700000];void insert(char key[]){int i=0;node *p= tire;while(key[i]){int k= key[i]-'a';if(p->next [k]==NULL) p->next [k] =new node();p=p->next[k] ;i++;}p->cnt ++;}void bfs(){int i,front=0,rear=0;tire->fail =NULL;que[rear++]= tire;while(rear!=front){node *temp =que[front++];for(i=0;i<26;i++){if(temp->next [i]!=NULL){if(temp== tire) temp->next [i]->fail  =tire;else{node *p= temp->fail ;while(p!=NULL){if(p->next [i]!=NULL){temp->next [i]->fail =p->next [i];break; }p=p->fail ;}if(p==NULL) temp->next [i]->fail =tire;}que[rear++]=temp->next [i];}}}}int getans(char des[]){int i=0,index,count=0;node * p= tire;while(des[i]){index = des[i]-'a';while(p->next [index]==NULL&&p!=tire) p= p->fail ;p=p->next [index];if(p==NULL) p= tire;node * temp =p;while(temp!=tire &&temp->cnt !=-1){count+=temp->cnt ;temp->cnt =-1;temp= temp->fail ;}i++;}return count;}int main(){int T,n;cin>>T;while(T--){tire = new node();for(int i=0;i<26;i++) tire->next [i]= NULL;tire->fail = NULL;cin>>n;for(int i=1;i<=n;i++){char key[60];scanf("%s",key);insert(key);}bfs();char des[1000001];scanf("%s",des);printf("%d\n",getans(des));}return 0;}


原创粉丝点击