AC自动机模板

来源:互联网 发布:入党申请书 知乎 编辑:程序博客网 时间:2024/06/09 22:07

我是在kuangbin巨巨的模板的基础上加上了初始化和模式串的插入。

代码:

struct Trie{int next[MAXN][26], fail[MAXN], end[MAXN];int root, L;void insert(char buf[]){int len = strlen(buf), now = 0;for(int i = 0; i < len; i++){if(next[now][buf[i] - 'a'] == -1) next[now][buf[i] - 'a'] = ++L;now = next[now][buf[i] - 'a'];}end[now]++;}void init()//不要忘记初始化{root = L = 0;memset(next, -1, sizeof(next));memset(fail, 0, sizeof(fail));memset(end, 0, sizeof(end)); }void build(){queue<int>q; fail[root] = root;for(int i = 0; i < 26; 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 < 26; 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 query(char buf[]){int len = strlen(buf); int now = root; int res = 0;for(int i = 0; i < len; i++){now = next[now][buf[i] - 'a'];int tmp = now;while(tmp != root){res += end[tmp];end[tmp] = 0;//注意这句话根据题来改变tmp = fail[tmp];}}return res;}};