HDU 2222 Keywords Search(AC自动机入门题)

看完了《训练指南》AC自动机这部分,找个入门题练练手。

题意比较简单,就是给N个串(可能有相同的,得重复计),然后给一个文本,统计N个串中有多少个在文本中出现。

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

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char s[1000010];
int t, n, ans;
struct ACAuto{
    int ch[1000010][26];
    int val[1000010];
    int f[1000010], last[1000010];
    int sz;
    void init(){
        sz=1;
        memset(ch[0],0,sizeof(ch[0]));
    }
    int idx(char ch){
        return ch-'a';
    }
    void insert(){
        int len=strlen(s);
        int u=0;
        int c;
        for(int i=0; i<len; i++){
            c=idx(s[i]);
            if(!ch[u][c]){
                val[sz]=0;
                memset(ch[sz],0,sizeof(ch[sz]));
                ch[u][c]=sz++;
            }
            u=ch[u][c];
        }
        val[u]++;
    }
    void getfail(){
        queue<int> Q;
        f[0]=0;
        for(int c=0; c<26; c++){
            int u=ch[0][c];
            if(u){
                f[u]=0; Q.push(u); last[u]=0;
            }
        }
        while(!Q.empty()){
            int r=Q.front(); Q.pop();
            for(int c=0; c<26; c++){
                int u=ch[r][c];
                if(!u)  continue;
                Q.push(u);
                int v=f[r];
                while(v&&!ch[v][c]) v=f[v];
                f[u]=ch[v][c];
                last[u]=val[f[u]]?f[u]:last[f[u]];
            }
        }
    }
    void cal(int x){
        while(x){
            ans+=val[x];
            val[x]=0;
            x=last[x];
        }
    }
    void find(){
        int len=strlen(s);
        int j=0;
        for(int i=0; i<len; i++){
            int c=idx(s[i]);
            while(j && !ch[j][c])   j=f[j];
            j=ch[j][c];
            cal(j);
        }
        printf("%d\n",ans);
    }
}ac;
int main(){
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        ac.init();
        while(n--){
            scanf("%s", s);
            ac.insert();
        }
        ac.getfail();
        scanf("%s", s);
        ans=0;
        ac.find();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值