hdu2222

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2222

题意:AC自动机模板题。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int maxnnode=500005;
const int ss=26;
int ans;
struct node{
    int ch[maxnnode][ss],last[maxnnode];
    int fail[maxnnode],val[maxnnode];
    int sz;

    void init(){
        memset(ch[0],0,sizeof(ch[0]));
        sz=1;
    }

    int idx(char c){return c-'a';}

    void insert(char* s){
        int u=0,n=strlen(s);
        for(int i=0;i<n;i++){
            int c=idx(s[i]);
            if(!ch[u][c]){
                memset(ch[sz],0,sizeof(ch[sz]));
                val[sz]=0;
                ch[u][c]=sz++;
            }
            u=ch[u][c];
        }
        val[u]++;
    }

    void getfail(){
        queue<int>q;
        fail[0]=0;
        for(int c=0;c<ss;c++){
            int u=ch[0][c];
            if(u){fail[u]=0;q.push(u);last[u]=0;}
        }
        while(!q.empty()){
            int r=q.front();    q.pop();
            for(int c=0;c<ss;c++){
                int u=ch[r][c];
                if(!u) {ch[r][c]=ch[fail[r]][c];continue;}
                q.push(u);
                fail[u]=ch[fail[r]][c];
                last[u]=val[fail[u]]?fail[u]:last[fail[u]];
            }
        }
    }

    void print(int j){
        if(j){
            ans+=val[j];
            val[j]=0;
            print(last[j]);
        }
    }

    void find(char* T){
        int n=strlen(T);
        int j=0;
        for(int i=0;i<n;i++){
            int c=idx(T[i]);
            j=ch[j][c];
            if(val[j]){
                print(j);
            }
            else{
                if(last[j]) print(last[j]);
            }
        }
    }
};
node ac;
char sss[1000005],tt[55];
int main(){
    int T;
    cin>>T;
    while(T--){
        int n;
        cin>>n;
        ac.init();
        while(n--){
            scanf("%s",tt);
            ac.insert(tt);
        }
        ac.getfail();
        scanf("%s",sss);
        ans=0;
        ac.find(sss);
        cout<<ans<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值