记录模板在文本中出现的次数,模板题。
AC代码:
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int size = 128;
const int MAX = 1010 * 55 + 10;
char T[2000010];
char buf[1010][100];
struct Trie{
int next[MAX][size],end[MAX],fail[MAX];
int root, L;
int newnode(){
for(int i=0; i<size; i++)
next[L][i] = -1;
end[L++] = -1;
return L - 1;
}
void init(){
L = 0;
root = newnode();
}
void insert(char buf[], int id){
int len = strlen(buf), now = root;
for(int i=0; i<len; i++){
if(next[now][buf[i]] == -1)
next[now][buf[i]] = newnode();
now = next[now][buf[i]];
}
end[now] = id;
}
void build(){
queue <int> Q;
fail[root] = root;
for(int i=0; i<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<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 cnt[1010];
void query(char T[], int n){
memset(cnt, 0, sizeof(cnt));
int len = strlen(T), now = root;
for(int i=0; i<len; i++){
now = next[now][T[i]];
int temp = now;
while(temp != root){
if(end[temp] != -1)
cnt[end[temp]]++;
temp = fail[temp];
}
}
for(int i=1; i<=n; i++)
if(cnt[i]) printf("%s: %d\n",buf[i], cnt[i]);
}
}AC;
int main(){
int n;
while(scanf("%d",&n) != EOF){
AC.init();
for(int i=1; i<=n; i++){
scanf("%s",buf[i]);
AC.insert(buf[i], i);
}
AC.build();
scanf("%s",T);
AC.query(T, n);
}
return 0;
}