AC Automaton Template ...
/* *AC Automaton Template * Use method: * 1, init (): Initialization function * 2, insert (str): Insert String function * 3, build (): Build AC Automaton, Query (str): Returns the number of strings that appear * * Use NOTE: * 1, note the scope of the input characters, you need to change the next and second dimension and related parameters * 2, pay attention to the size of next, fail and end array, prevent over-memory group out of bounds * 3, according to the actual situation of the template "Buf[i"-' a ' "change, otherwise the array may be out of bounds * The default settings for this template are: * 1, the total length of the short string is not more than 500000 * 2, the content of the input string is composed only of lowercase letters A~Z * 3, the query () function only counts the number of matches *ps: all of the above needs to be changed according to the need!!! */#include <stdio.h> #include <algorithm> #include <iostream> #include <string.h> #include < Queue>using namespace Std;int next[500010][26], fail[500010], end[500010];int root, L;int NewNode () {for (int i = 0; i < 26; i++) Next[l][i] =-1; end[l++] = 0;return L-1;} void Init () {L = 0;root = NewNode ();} void Insert (char buf[]) {int len = strlen (BUF); int now = root;for (int i = 0; i < len; i++) {if (Next[now][buf[i]-' a ' ] = =-1) next[now][buf[i]-' a '] = NewNode (); now = next[now][buf[i]-' a '];} end[now]++;} void Build () {queue<int>q; Fail[root] = root;for (int i = 0; i <; 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 <; 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 temp = now;while (temp! = root) {res + = End[temp]; End[temp] = 0;temp = Fail[temp];}} return res;} int main () {freopen ("in.in", "R", stdin), Freopen ("Out.out", "w", stdout); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
AC Automaton Template