hdu2222

ac自动机入门,基础模板
先看的白书,没看懂。
再找的大牛模板,虽然慢了点,好歹看懂了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int sigma_size = 28;
const int maxnode = 500005;
struct Trie{
    int ch[maxnode][sigma_size];
    int val[maxnode];
    int f[maxnode];
    int root,L;
    int newnode(){
        for(int i = 0;i < sigma_size;i++){
            ch[L][i] = -1;
        }
        val[L++] = 0;
        return L - 1;
    }
    void init()
    {
        L = 0;
        root = newnode();
    }
    int idx(char x){
        return x - 'a';
    }
    void Insert(char *s){
        int len = strlen(s);
        int now = root;
        for(int i = 0;i < len;i++){
            int c = idx(s[i]);
            if(ch[now][c] == -1){
                ch[now][c] = newnode();
            }
            now = ch[now][c];
        }
        val[now]++;
    }
    void getFail(){
        queue<int> q;
        f[root] = root;
        for(int i = 0;i < sigma_size;i++){
            if(ch[root][i] == -1){
                ch[root][i] = root;
            }
            else {
                f[ch[root][i]] = root;
                q.push(ch[root][i]);
            }
        }
        while(!q.empty()){
            int now = q.front();q.pop();
            for(int i = 0;i < sigma_size;i++){
                if(ch[now][i] == -1){
                    ch[now][i] = ch[f[now]][i];
                }
                else
                {
                    f[ch[now][i]] = ch[f[now]][i];
                    q.push(ch[now][i]);
                }
            }
        }
    }
    int Find(char *s){
        int len = strlen(s);
        int now = root;
        int res = 0;
        for(int i = 0;i < len;i++){
            int c = idx(s[i]);
            now = ch[now][c];
            int tmp = now;
            while(tmp != root){
                res += val[tmp];
                val[tmp] = 0;
                tmp = f[tmp];
            }
        }
        return res;
    }
};


Trie ac;
char buf[1000020];
int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
        int n;
        scanf("%d",&n);
        ac.init();
        while(n--){
            scanf("%s",buf);
            ac.Insert(buf);
        }
        ac.getFail();
        scanf("%s",buf);
        int ans = ac.Find(buf);
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值