HDU 3065 病毒侵袭持续中——AC自动机

注意文本串为可见字符,套用模板时不能单纯的减去'A',一种解决方法是把SIZE开到128,不过这样非常不负责任。。。另一种解决方法是在查找时找到大写字母以外的字符就把root设为0,并且continue;注意不能预处理出大写字母,否则AxxxxxA会预处理出AA,如果模式串为AA就出错了(当然预处理也有一种解决方法,不过挺麻烦,不推荐)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int MAXL = 2 * 1e6 + 10;
const int MAXN = 1e5;
const int SIZE = 26;

char str1[1010][55], str2[MAXL];
int n, ans[1010];
struct AC {
    int total, val[MAXN], fail[MAXN], child[MAXN][SIZE];
    void init() {
        total = 1;
        memset(val, 0, sizeof(val));
        memset(fail, 0, sizeof(fail));
        memset(child[0], 0, sizeof(child[0]));
    }
    void Insert(char *P, int id) {
        int len = strlen(P), root = 0;
        for (int i = 0; i < len; i++) {
            if (!child[root][P[i] - 'A']) {
                memset(child[total], 0, sizeof(child[total]));
                child[root][P[i] - 'A'] = total++;
            }
            root = child[root][P[i] - 'A'];
        }
        val[root] = id;
    }
    void Getfail() {
        queue<int> q;
        for (int i = 0; i < SIZE; i++) {
            if (child[0][i]) q.push(child[0][i]);
        }
        while (!q.empty()) {
            int root = q.front(); q.pop();
            for (int i = 0; i < SIZE; i++) {
                int u = child[root][i];
                if (!u) { child[root][i] = child[fail[root]][i]; continue; }
                q.push(u);
                int v = fail[root];
                while (v && !child[v][i]) v = fail[v];
                fail[u] = child[v][i];
            }
        }
    }
    void Search(char *T) {
        Getfail();
        int len = strlen(T), root = 0, temp;
        for (int i = 0; i < len; i++) {
            if ('Z' < T[i] || T[i] < 'A') { root = 0; continue; }
            temp = root = child[root][T[i] - 'A'];
            while (temp && val[temp]) {
                ans[val[temp]]++;
                temp = fail[temp];
            }
        }
    }
}ac;

int main()
{
    while (~scanf("%d", &n)) {
        memset(ans, 0, sizeof(ans));
        ac.init();
        for (int i = 1; i <= n; i++) {
            scanf("%s", str1[i]); ac.Insert(str1[i], i);
        }
        getchar(); gets(str2);
        ac.Search(str2);
        for (int i = 1; i <= n; i++) {
            if (ans[i]) {
                printf("%s: %d\n", str1[i], ans[i]);
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值