Test instructions: Give a string and several templates to find out the number of templates that appear in the text string.
Idea: Because there may be duplicate templates, trie tree weights record the number of times each template appears.
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <iostream > #include <algorithm> #include <vector> #include <map> #include <queue> #include <stack > #include <string> #include <map> #include <set> #include <ctime> #define EPS 1e-6#define LL Long Long#define PII (Pair<int, int>)//#pragma comment (linker, "/stack:1024000000,1024000000") using namespace std;const int MAXN = 1000000 + 100;const int sigma_size = 26;const int maxnode = 1000000+100;int N, ans;bool Vis[maxn];map <string, int> Ms;int ch[maxnode][sigma_size+5]; int Val[maxnode]; int idx (char c) {return C-' a ';} struct Trie {int sz; Trie () {sz = 1; memset (Ch[0], 0, sizeof (ch[0])); memset (Vis, 0, sizeof (VIS));} void Insert (char *s) {int u = 0, n = strlen (s); for (int i = 0; i < n; i++) {int c = idx (s[i]); if (!ch[u][c]) {memset (Ch[sz], 0, SizeoF (Ch[sz])); Val[sz] = 0; CH[U][C] = sz++; } u = Ch[u][c]; } val[u]++; } }; AC automaton int LAST[MAXN], f[maxn];void print (int j) {if (J &&!vis[j]) {ans + = val[j]; Vis[j] = 1;print (Last[j]);} in T Getfail () {queue<int> q;f[0] = 0;for (int c = 0; c < sigma_size; C + +) {int u = ch[0][c];if (u) {f[u] = 0; Q.push ( u); Last[u] = 0;}} while (!q.empty ()) {int r = Q.front (), Q.pop (); for (int c = 0; c < sigma_size; C + +) {int u = ch[r][c];if (!u) {Ch[r][c] = Ch[f[r]][c];continue;} Q.push (u); int v = f[r];while (v &&!ch[v][c]) v = f[v];f[u] = Ch[v][c];last[u] = Val[f[u]]? F[u]: Last[f[u] ";}}} void find_t (char* t) {int n = strlen (t); int j = 0;for (int i = 0; i < n; i++) {int c = idx (T[i]); j = ch[j][c];if (Val[j]) Print (j); else if (Last[j]) print (Last[j]);}} Char Tmp[105];char text[1000000+1000];int Main () {//freopen ("Input.txt", "R", stdin); int T; CIN >> T;while (t--) {scanf ("%d", &n); Trie TRIe;ans = 0;for (int i = 0; i < n; i++) {scanf ("%s", TMP); Trie.insert (TMP);} Getfail (); scanf ("%s", text); find_t (text); cout << ans << endl;} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 2222 Keywords Search (AC automaton template problem)