Title Link: Keywords Search
Parse: Directly open an end array, statistics can be.
The code style of the Ps:ac automata is reference bin God.
AC Code:
#include <bits/stdc++.h>using namespace Std;const int max_word = 500005;const int sigma_size = 26;const int Max_text = 1000005;struct trie{int next[max_word][sigma_size], Fail[max_word], End[max_word]; int root, L; int NewNode () {for (int i = 0; i < sigma_size; 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 < sigma_size; 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 < sigma_size; 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; } void Debug () {for (int i = 0; i < L; i++) {printf ("id =%3d, fail =%3d, end =%3d, Chi = [", I, Fail[i], end[i]); for (int j = 0; J < Sigma_size; J + +) printf ("%2d", Next[i][j]); printf ("]\n"); } }};char Buf[max_text]; Trie Ac;int Main () {#ifdef sxk freopen ("In.txt", "R", stdin); #endif//Sxk int T, n; scanf ("%d", &t); while (t--) {scanf ("%d", &n); Ac.init (); for (int i = 0; i < n; i++) {scanf ("%s", buf); Ac.insert (BUF); } ac.build (); scanf ("%s", buf); printf ("%d\n", Ac.query (BUF)); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 2222 Keywords Search (AC automaton)