1 /*
2 题意:每个文本串的出现次数
3 AC自动机:入门题,注意关键词重复和出现过的关键词的次数不算到总数内
4 */
5 /************************************************
6 * Author :Running_Time
7 * Created Time :2015-8-14 14:14:32
8 * File Name :AC.cpp
9 ************************************************/
10
11 #include <cstdio>
12 #include <algorithm>
13 #include <iostream>
14 #include <sstream>
15 #include <cstring>
16 #include <cmath>
17 #include <string>
18 #include <vector>
19 #include <queue>
20 #include <deque>
21 #include <stack>
22 #include <list>
23 #include <map>
24 #include <set>
25 #include <bitset>
26 #include <cstdlib>
27 #include <ctime>
28 using namespace std;
29
30 #define lson l, mid, rt << 1
31 #define rson mid + 1, r, rt << 1 | 1
32 typedef long long ll;
33 const int MAXN = 1e4 + 10;
34 const int MAXNODE = MAXN * 50 + 10;
35 const int INF = 0x3f3f3f3f;
36 const int SIGMA_SIZE = 26;
37 const int MOD = 1e9 + 7;
38 struct AC {
39 int ch[MAXNODE][SIGMA_SIZE], f[MAXNODE], sz;
40 int val[MAXNODE];
41 void init(void) {
42 memset (ch[0], 0, sizeof (ch[0]));
43 sz = 1; val[0] = 0;
44 }
45 int idx(char c) {
46 return c - ‘a‘;
47 }
48 void insert(char *s) {
49 int u = 0;
50 for (int i=0; s[i]; ++i) {
51 int c = idx (s[i]);
52 if (!ch[u][c]) {
53 memset (ch[sz], 0, sizeof (ch[sz]));
54 val[sz] = 0;
55 ch[u][c] = sz++;
56 }
57 u = ch[u][c];
58 }
59 val[u]++;
60 }
61 void build(void) {
62 queue<int> Q; f[0] = 0;
63 for (int i=0; i<SIGMA_SIZE; ++i) {
64 int u = ch[0][i];
65 if (u) {
66 f[u] = 0; Q.push (u);
67 }
68 else ch[0][i] = 0;
69 }
70 while (!Q.empty ()) {
71 int u = Q.front (); Q.pop ();
72 for (int i=0; i<SIGMA_SIZE; ++i) {
73 int &v = ch[u][i];
74 if (!v) {
75 v = ch[f[u]][i]; continue;
76 }
77 Q.push (v);
78 f[v] = ch[f[u]][i];
79 }
80 }
81 }
82 int query(char *T) {
83 int ret = 0; int j = 0;
84 for (int i=0; T[i]; ++i) {
85 int c = idx (T[i]);
86 j = ch[j][c];
87 int u = j;
88 while (u) {
89 ret += val[u]; val[u] = 0;
90 u = f[u];
91 }
92 }
93 return ret;
94 }
95 }ac;
96 char p[55], t[1000010];
97
98 int main(void) { //HDOJ 2222 Keywords Search
99 int T; scanf ("%d", &T);
100 while (T--) {
101 int n; scanf ("%d", &n);
102 ac.init ();
103 for (int i=1; i<=n; ++i) {
104 scanf ("%s", p); ac.insert (p);
105 }
106 ac.build (); scanf ("%s", t);
107 printf ("%d\n", ac.query (t));
108 }
109
110 return 0;
111 }
AC自动机 HDOJ 2222 Keywords Search
原文:http://www.cnblogs.com/Running-Time/p/4737729.html