• AC自动机模板


    const int SIGMA_SIZE = 26;
    const int MAXNODE = 11000;
    struct AhoCorasickAutomata {
        int ch[MAXNODE][SIGMA_SIZE];
        int f[MAXNODE];    // fail函数
        int val[MAXNODE];  // 每个字符串的结尾结点都有一个非0的val
        int last[MAXNODE]; // 输出链表的下一个结点
        int sz;
    
        void init() {
            sz = 1;
            memset(ch[0], 0, sizeof(ch[0]));
        }
        // 字符c的编号
        int idx(char c) {
            return c-'a';
        }
    
        // 插入字符串。v必须非0
        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;
        }
    
        // 递归打印以结点j结尾的所有字符串
        void print(int j) {
            if(j) {
    
                print(last[j]);
            }
        }
    
        // 在T中找模板
        int find(char* T) {
            int n = strlen(T);
            int j = 0; // 当前结点编号,初始为根结点
            for(int i = 0; i < n; i++) { // 文本串当前指针
                int c = idx(T[i]);
                while(j && !ch[j][c]) j = f[j];
                j = ch[j][c];
                if(val[j]) print(j);
                else if(last[j]) print(last[j]); // 找到了!
            }
        }
    
        // 计算fail函数
        void getFail() {
            queue<int> q;
            f[0] = 0;
            // 初始化队列
            for(int c = 0; c < SIGMA_SIZE; c++) {
                int u = ch[0][c];
                if(u) {
                    f[u] = 0;
                    q.push(u);
                    last[u] = 0;
                }
            }
            // 按BFS顺序计算fail
            while(!q.empty()) {
                int r = q.front(); q.pop();
                for(int c = 0; c < SIGMA_SIZE; c++) {
                    int u = ch[r][c];
                    if(!u) continue;
                    q.push(u);
                    int v = f[r];
                    while(v && !ch[v][c]) v = f[v];
                    f[u] = ch[v][c];
                    last[u] = val[f[u]] ? f[u] : last[f[u]];
                }
            }
        }
    };
  • 相关阅读:
    同志们的毒害1_xuhang01
    2019佳木斯集训 Day8
    2019佳木斯集训 Day7
    2019佳木斯集训 Day6
    2019佳木斯集训 Day5
    数据结构——关于倍增LCA那点事
    2019佳木斯集训 Day3
    2019佳木斯集训 Day4
    centos7安装python2 sybase相关依赖
    mac与centos终端快捷指令
  • 原文地址:https://www.cnblogs.com/033000-/p/10363312.html
Copyright © 2020-2023  润新知