HDU3695 Computer Virus on Planet Pandora

来源:互联网 发布:淘宝白菜价优惠券秒杀 编辑:程序博客网 时间:2024/05/17 22:51

微微发亮的传送门

AC自动机模板题,终于找到了个内存限制比较宽松的。。HDU2222真心是2啊……内存限制太窘迫了。

#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;int ans = 0;struct ACautomata{    int ch[250001][27], val[250001];    int f[250010], sz;    void reset(){        memset(ch[0], 0, sizeof(ch[0]));        memset(val, 0, sizeof(val));        sz = 1;    }    int idx(char c){        return c - 'A';    }    void insert(char *s, int v){        int u = 0, n = strlen(s);        for (int i = 0; i < n; i++){            int c = idx(s[i]);            if (!ch[u][c]){                memset(ch[sz], 0, sizeof(ch[sz]));                val[sz] = 0;                ch[u][c] = sz++;            }            u = ch[u][c];        }        val[u] = v;    }    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);}        }        while(!q.empty()){            int r = q.front(); q.pop();            for (int c = 0; c < 26; c++){                int u = ch[r][c];                if (!u){ch[r][c] = ch[f[r]][c]; continue;}                q.push(u);                int v = f[r];                while(v && !ch[v][c]) v = f[v];                f[u] = ch[v][c];            }        }    }    void find(char *T){        int n = strlen(T);        int j = 0;        for (int i = 0; i < n; i++){            int c = idx(T[i]);            j = ch[j][c];            int tmp = j;            while(tmp && val[tmp]){                ans += 1;                val[tmp] = 0;                tmp = f[tmp];            }        }    }}ac;char s[1111], c1[6000009], c2[6000009];int main(){    int t;    scanf("%d", &t);    while(t--){        ac.reset();        int n;        scanf("%d", &n);        while (n--){            scanf("%s", s);            ac.insert(s, 1);        }        ac.getfail();        scanf("%s", c2);        int l = strlen(c2);        int m = 0;        for(int i = 0; i < l; i++)            if(c2[i] >= 'A' && c2[i] <= 'Z')                c1[m++] = c2[i];            else if(c2[i] >= '0' && c2[i] <= '9'){                int k = c2[i++] - '0';                while(c2[i] >= '0' && c2[i] <= '9'){                    k = 10 * k + c2[i++] - '0';                }                char cc = c2[i];                for(int j = 0; j < k; j++)                    c1[m++] = cc;            }        c1[m] = 0;        ans = 0;        ac.find(c1);        l = strlen(c1);        reverse(c1, c1 + l);        ac.find(c1);        printf("%d\n", ans);    }}