题意:需要统计每一个单词在文本中出现的次数
没有重复的单词,直接拿来跑自动机就好.
#include <bits/stdc++.h>
using namespace std;
#define maxn 51111
#define maxm 2111111
int n, m;
char str[1111][55];
char a[maxm];
struct trie {
int next[maxn][110], fail[maxn], end[maxn];
int root, cnt;
int num[maxn];
int f[maxn];
int new_node () {
memset (next[cnt], -1, sizeof next[cnt]);
end[cnt++] = 0;
return cnt-1;
}
void init () {
cnt = 0;
root = new_node ();
memset (f, -1, sizeof f);
memset (num, 0, sizeof num);
}
void insert (char *buf, int pos) {
int len = strlen (buf);
int now = root;
for (int i = 0; i < len; i++) {
int id = buf[i]-20;
if (next[now][id] == -1) {
next[now][id] = new_node ();
}
now = next[now][id];
}
end[now]++;
f[now] = pos;
}
void build () {
queue <int> q;
fail[root] = root;
for (int i = 0; i < 110; 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 < 110; 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;
for (int i = 0; i < len; i++) {
int id = buf[i]-20;
now = next[now][id];
int tmp = now;
while (tmp != root) {
if (end[tmp]) {
num[f[tmp]] += end[tmp];
}
tmp = fail[tmp];
}
}
for (int i = 1; i <= n; i++) {
if (num[i]) {
printf ("%s: %d\n", str[i], num[i]);
}
}
return 0;
}
}ac;
int main () {
while (scanf ("%d", &n) == 1) {
ac.init ();
for (int i = 1; i <= n; i++) {
scanf ("%s", str[i]);
ac.insert (str[i], i);
}
ac.build ();
scanf ("%s", a);
ac.query (a);
}
return 0;
}