HDU-2222-Aho-Corasick--自动机

来源:互联网 发布:机柜网络模块接线图 编辑:程序博客网 时间:2024/05/01 08:15

模板题目

理解了AC自动机之后感觉这真是一个奇妙的东西▼o・ェ・o▼

参考  http://blog.csdn.net/zxy_snow/article/details/6709255

#include<iostream>#include<cstring>#include<cstdio>#include<queue>using namespace std;const int SIGMA_SIZE = 26;struct node{node * ch[SIGMA_SIZE];node * back;int cnt;node(){back=NULL;cnt=0;for(int i=0;i<SIGMA_SIZE;i++)ch[i]=NULL;}};node * root;int idx(const char c){return c-'a';}void insert(const char *s){int c,len =strlen(s);node *u=root;for(int i=0;i<len;i++){c=idx(s[i]);if(u->ch[c]==NULL){u->ch[c]=new node();}u=u->ch[c];}u->cnt++;}void getFail(){queue<node *> q;q.push(root);node *now,*p;while(!q.empty()){now=q.front();q.pop();for(int i=0;i<SIGMA_SIZE;i++){if(now->ch[i]){p=now->back;while(p){if(p->ch[i]){now->ch[i]->back=p->ch[i];break;}p=p->back;}if(p==NULL)now->ch[i]->back = root;q.push(now->ch[i]);}}}}int ans =0 ;void find(const char *t){ans=0;node * u=root;int len = strlen(t);for(int i=0;i<len;i++){int c = idx(t[i]);while(u->ch[c]==NULL&&u!=root){u=u->back;}u=u->ch[c]==NULL?root:u->ch[c];node * temp = u;while(temp!=root&&temp->cnt>0){ans+=temp->cnt;temp->cnt=-1;temp = temp->back;}}}char t[1000090];int main(){freopen("data.in","r",stdin);char s[100];int n,T;scanf("%d",&T);while(T--){root=new node();scanf("%d",&n);while(n--){scanf("%s",s);insert(s);}getFail();scanf("%s",t);find(t);printf("%d\n", ans);}return 0;}

板子留着


原创粉丝点击