【模板】AC自动机

来源:互联网 发布:16年淘宝卖零食要证吗 编辑:程序博客网 时间:2024/05/17 02:50

这里写图片描述

#include<bits/stdc++.h>using namespace std;int n,ans;char a[1000005],b[1000005];int tim;struct trie{    trie *nex;    trie *ch[26];    int sum;}*root=new trie;inline void insert(char *b){    trie *p=root;    for(int i=0;b[i];++i){        int x=b[i]-'a';        if(p->ch[x]==NULL){            p->ch[x]=new trie;            for(int j=0;j<=25;++j)   p->ch[x]->ch[j]=NULL;            p->ch[x]->nex=NULL;            p->ch[x]->sum=0;        }        p=p->ch[x];    }    ++p->sum;}inline void getnex(){    trie *temp;    queue<trie*>q;    q.push(root);    while(!q.empty()){        temp=q.front();q.pop();        for(int i=0;i<=25;++i){            if(temp->ch[i]==NULL)    continue;            if(temp==root)      temp->ch[i]->nex=root;            else{                trie *p=temp->nex;                while(p!=NULL){                    if(p->ch[i]!=NULL){                        temp->ch[i]->nex=p->ch[i];                        break;                    }                    p=p->nex;                }                if(p==NULL) temp->ch[i]->nex=root;            }            q.push(temp->ch[i]);        }    }}inline void ac_auto(char *a){    trie *p=root;    for(int i=0;a[i];++i){        int x=a[i]-'a';        while(!p->ch[x] && p!=root)  p=p->nex;        p=p->ch[x];        if(p==NULL) p=root;        trie *temp=p;        while(temp!=root){            if(temp->sum >= 0){                ans+=temp->sum;                temp->sum=-1;            }            else    break;            temp=temp->nex;        }    }}int main(){    for(int i=0;i<=25;++i)   root->ch[i]=NULL;root->nex=NULL;root->sum=0;    scanf("%s",a);    scanf("%d",&n);    for(int i=1;i<=n;++i){        scanf("%s",b);        insert(b);    }    getnex();    ac_auto(a);    printf("%d",ans);    return 0;}
原创粉丝点击