HDU 2896 病毒侵袭——AC自动机

来源:互联网 发布:照片模板软件 编辑:程序博客网 时间:2024/05/20 14:24

数组开小了却提示TLE。。。真讨厌

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <queue>using namespace std;const int MAXN = 1e5 + 10;const int MAXL = 1e4 + 10;const int SIZE = 128;char str[MAXL];int N, M;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]]) {                memset(child[total], 0, sizeof(child[total]));                child[root][P[i]] = total++;            }            root = child[root][P[i]];        }        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];            }        }    }    bool Search(char *T, int id) {        bool ok = false;        int len = strlen(T), root = 0, temp;        int cnt = 0, ans[10], vis[1000] = {0};        for (int i = 0; i < len; i++) {            temp = root = child[root][T[i]];            while (temp && val[temp]) {                if (!vis[val[temp]]) {                    vis[val[temp]] = 1;                    ans[cnt++] = val[temp];                    ok = true;                }                if (cnt == 3) break;                temp = fail[temp];            }        }        if (ok) {            printf("web %d:", id);            sort(ans, ans + cnt);            for (int i = 0; i < cnt; i++) {                printf(" %d", ans[i]);            }            printf("\n");        }        return ok;    }}ac;int main() {        ac.init();        scanf("%d", &N);        for (int i = 1; i <= N; i++) {            scanf("%s", str); ac.Insert(str, i);        }        ac.Getfail();        int sum = 0;        scanf("%d", &M);        for (int i = 1; i <= M; i++) {            scanf("%s", str);            if (ac.Search(str, i)) sum++;        }        printf("total: %d\n", sum);}


原创粉丝点击