点击打开链接题目链接
1 5 she he say shr her yasherhs
3
ac自动机模板题
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
char str1[55],str2[1111111];
struct node{
    node *fail,*next[26];
    int ed;
    node(){
        ed=0;
        fail=NULL;
        for(int i=0;i<26;i++)
            next[i]=NULL;
    }
}*q[511111],*root;
void tree_insert(char *str){
    node *p=root;
    int l=strlen(str);
    int id;
    for(int i=0;i<l;i++){
        id=str[i]-'a';
        if(p->next[id]==NULL){
            p->next[id]=new node();
        }
        p=p->next[id];
    }
    p->ed++;
}
void build_ac_automachine(){
    int i;
    node *temp,*p;
    root->fail=NULL;
    int fr,ed;
    fr=ed=0;
    q[ed++]=root;
    while(fr<ed){
        temp=q[fr++];
        for(i=0;i<26;i++){
            if(temp->next[i]!=NULL){
                if(temp==root)
                    temp->next[i]->fail=root;
                else {
                    p=temp->fail;
                    while(p){
                        if(p->next[i]){
                            temp->next[i]->fail=p->next[i];
                            break;
                        }
                        p=p->fail;
                    }
                    if(p==NULL)
                        temp->next[i]->fail=root;
                }
                q[ed++]=temp->next[i];
            }
        }
    }
}
int query(char *str){
    int cnt=0;
    int l=strlen(str);
    node *p=root;
    for(int i=0;i<l;i++){
        int id=str[i]-'a';
        while(p->next[id]==NULL&&p!=root)
            p=p->fail;
        p=p->next[id];
        if(p==NULL)
            p=root;
        node *temp=p;
        while(temp!=root&&temp->ed!=-1){
            cnt+=temp->ed;
            temp->ed=-1;
            temp=temp->fail;
        }
    }
    return cnt;
}
int main(){
    int t,n;
    scanf("%d",&t);
    while(t--){
        root=new node();
        scanf("%d",&n);
        while(n--){
            scanf("%s",str1);
            tree_insert(str1);
        }
        scanf("%s",str2);
        build_ac_automachine();
        printf("%d\n",query(str2));
    }
    return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu 2222 Keywords Search ac自动机
原文地址:http://blog.csdn.net/qq_16843991/article/details/46893817