Link to the question: hdu 2222 Keywords Search
A character set is provided, indicating a keyword. Now there is a string and you can ask how many matching keywords are there.
Solution: AC automatic machine. Pay attention to the same keywords. If the same keyword appears twice, calculate one.
# Include <cstdio> # include <cstring> # include <queue> # include <set> # include <algorithm> using namespace std; const int maxn = 500005; const int maxl = 1e6 + 5; const int sigma_size = 26; struct Aho_Corasick {int sz, g [maxn] [sigma_size]; int tag [maxn], jump [10005]; int fail [maxn], last [maxn]; int ans, vis [10005]; void init (); int idx (char ch); void insert (char * str, int k); void getFail (); void match (char * Str); void put (int u);} A; char s [maxl], w [55]; int main () {int cas, n; scanf ("% d", & cas); while (cas --) {. init (); scanf ("% d", & n); for (int I = 1; I <= n; I ++) {scanf ("% s ", w);. insert (w, I);}. getFail (); scanf ("% s", s);. match (s); printf ("% d \ n",. ans);} return 0;} void Aho_Corasick: init () {sz = 1; tag [0] = jump [0] = 0; memset (g [0], 0, sizeof (g [0]);} int Aho_Corasick: idx (char ch) {ret Urn ch-'A';} void Aho_Corasick: put (int u) {int p = tag [u]; while (p & vis [p] = 0) {ans ++; vis [p] = 1; p = jump [p];} if (last [u]) put (last [u]);} void Aho_Corasick :: match (char * str) {ans = 0; memset (vis, 0, sizeof (vis); int n = strlen (str), u = 0; for (int I = 0; I <n; I ++) {int v = idx (str [I]); while (u & g [u] [v] = 0) u = fail [u]; u = g [u] [v]; if (tag [u]) put (u); else if (last [u]) put (l Ast [u]) ;}} void Aho_Corasick: insert (char * str, int k) {int n = strlen (str), u = 0; for (int I = 0; I <n; I ++) {int v = idx (str [I]); if (g [u] [v] = 0) {tag [sz] = 0; memset (g [sz], 0, sizeof (g [sz]); g [u] [v] = sz ++ ;} u = g [u] [v];} jump [k] = tag [u]; tag [u] = k;} void Aho_Corasick: getFail () {queue <int> que; for (int I = 0; I <sigma_size; I ++) {int u = g [0] [I]; if (u) {fail [u] = last [u] = 0; Que. push (u) ;}} while (! Que. empty () {int r = que. front (); que. pop (); for (int I = 0; I <sigma_size; I ++) {int u = g [r] [I]; if (u = 0) {g [r] [I] = g [fail [r] [I]; continue;} que. push (u); int v = fail [r]; while (v & g [v] [I] = 0) v = fail [v]; fail [u] = g [v] [I]; last [u] = tag [fail [u]? Fail [u]: last [fail [u] ;}}
Hdu 2222 Keywords Search (AC automatic machine)