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

来源:互联网 发布:淘宝卖家火拼在哪里 编辑:程序博客网 时间:2024/05/20 14:24

注意文本串为可见字符,套用模板时不能单纯的减去'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;}


原创粉丝点击