您的位置:首页 > 其它

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

2015-08-01 00:01 357 查看
题目链接:病毒侵袭持续中

解析:用end数组标记病毒编号,用used数组记录各个病毒出现的次数,最后对应输出即可。

AC代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1002;
const int max_word = 52;
const int max_text = 2000002;
const int sigma_size = 128;

char buf[max_text], vir[maxn][max_word];      //vir[][]保存对应病毒序列

struct Trie{
    int next[max_word*maxn][sigma_size], fail[max_word*maxn], end[max_word*maxn];
    int root, L;

    int newnode(){
        for(int i = 0; i < sigma_size; i++) next[L][i] = -1;
        end[L++] = 0;
        return L-1;
    }

    void init(){
        L = 0;
        root = newnode();
    }

    void insert(char buf[], int id){
        int len = strlen(buf);
        int now = root;
        for(int i = 0; i < len; i++){
            if(next[now][ buf[i] ] == -1) next[now][ buf[i] ] = newnode();
            now = next[now][ buf[i] ];
        }
        end[now] = id;       //标记病毒编号
    }

    void build(){
        queue<int> Q;
        fail[root] = root;
        for(int i = 0; i < sigma_size; i++){
            if(next[root][i] == -1) next[root][i] = root;
            else{
                fail[ next[root][i] ] = root;
                Q.push(next[root][i]);
            }
        }
        while(!Q.empty()){
            int now = Q.front();
            Q.pop();
            for(int i = 0; i < sigma_size; i++){
                if(next[now][i] == -1) next[now][i] = next[ fail[now] ][i];
                else{
                    fail[ next[now][i] ] = next[ fail[now] ][i];
                    Q.push(next[now][i]);
                }
            }
        }
    }

    int used[maxn];         //计数
    int query(char buf[], int n){
        memset(used, 0, sizeof(used));
        int len = strlen(buf);
        int now = root;
        bool flag = false;
        for(int i = 0; i < len; i++){
            now = next[now][ buf[i] ];
            int temp = now;
            while(temp != root){
                if(end[temp]){
                    used[ end[temp] ] ++;
                    flag = true;
                }
                temp = fail[temp];
            }
        }
        if(flag){
            for(int i = 1; i <= n; i++)
                if(used[i]) printf("%s: %d\n", vir[i], used[i]);
        }
    }

    void debug(){
        for(int i = 0; i < L; i++){
            printf("id = %3d, fail = %3d, end = %3d, chi = [", i, fail[i], end[i]);
            for(int j = 0; j <sigma_size; j++) printf("%2d", next[i][j]);
            printf("]\n");
        }
    }
};

Trie ac;

int main(){
    #ifdef sxk
        freopen("in.txt", "r", stdin);
    #endif //sxk

    int n, m;
    while(scanf("%d", &n) == 1){
        ac.init();
        for(int i = 1; i <= n; i++){
            scanf("%s", vir[i]);
            ac.insert(vir[i], i);
        }
        ac.build();
        scanf("%s", buf);
        ac.query(buf, n);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: