zoukankan      html  css  js  c++  java
  • AC自动机

    class AC {
    public:
        int next[maxn][26], lst[maxn], fail[maxn], val[maxn];
        int sz, root;
        void init() {
            root = sz = 0;
            for (int i=0; i<26; ++i)
                next[sz][i] = 0;
            val[sz] = 0;
            sz = 1;
        }
        inline int getid(char ch) {
            return ch-'a';
        }
        inline int newnode() {
            for (int i=0; i<26; ++i)
                next[sz][i] = 0;
            val[sz] = 0;
            return sz++;
        }
        void insert(char s[]) {
            int rt, i, id, len;
            rt = 0; len = strlen(s);
            for (i=0; i<len; ++i) {
                id = getid(s[i]);
                if (!next[rt][id]) next[rt][id] = newnode();
                rt = next[rt][id];
            }
            val[rt]++;
        }
        void build() {
            queue<int> q;
            int i, rt, id;
            fail[root] = root;
            lst[root] = root;
            for (i=0; i<26; ++i) {
                if (!next[root][i]) next[root][i] = root;
                else {
                    fail[next[root][i]] = root;
                    q.push(next[root][i]);
                    lst[next[root][i]] = val[fail[next[root][i]]] ? fail[next[root][i]] : lst[fail[next[root][i]]];
                }
    
            }
            while (!q.empty()) {
                rt = q.front(); q.pop();
                for (i=0; i<26; ++i) {
                    if (!next[rt][i]) next[rt][i] = next[fail[rt]][i];
                    else {
                        fail[next[rt][i]] = next[fail[rt]][i];
                        q.push(next[rt][i]);
                        lst[next[rt][i]] = val[fail[next[rt][i]]] ? fail[next[rt][i]] : lst[fail[next[rt][i]]];
                    }
                }
            }
        }
        int query(char s[]) {
            int i, rt, tmp, now = 0, res = 0, len = strlen(s);
            for (i=0; i<len; ++i) {
                now = next[now][getid(s[i])];
                tmp = now;
                while (tmp) {
                    res += val[tmp];
                    val[tmp] = 0;
                    tmp = lst[tmp];
                }
            }
            return res;
        }
    };
     
  • 相关阅读:
    javascript_数组
    Javascript_函数
    JavaScript思维导图
    django 中session的存储和获取
    使用 PyCharm 在centos 部署代码
    mac下使用async-profiler
    Mac系统如何清理mysql
    Java-多线程
    Java内部类
    WinForm使用发布方式进行安装的安装目录
  • 原文地址:https://www.cnblogs.com/cgjh/p/9369658.html
Copyright © 2011-2022 走看看