题目链接:病毒侵袭持续中
解析:用end数组标记病毒编号,用used数组记录各个病毒出现的次数,最后对应输出即可。
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1002;
const int max_word = 52;
const int max_text = 2000002;
const int sigma_size = 128;
char buf[max_text], vir[maxn][max_word]; //vir[][]保存对应病毒序列
struct Trie{
int next[max_word*maxn][sigma_size], fail[max_word*maxn], end[max_word*maxn];
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 id){
int len = strlen(buf);
int 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 < 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 used[maxn]; //计数
int query(char buf[], int n){
memset(used, 0, sizeof(used));
int len = strlen(buf);
int now = root;
bool flag = false;
for(int i = 0; i < len; i++){
now = next[now][ buf[i] ];
int temp = now;
while(temp != root){
if(end[temp]){
used[ end[temp] ] ++;
flag = true;
}
temp = fail[temp];
}
}
if(flag){
for(int i = 1; i <= n; i++)
if(used[i]) printf("%s: %d\n", vir[i], used[i]);
}
}
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");
}
}
};
Trie ac;
int main(){
#ifdef sxk
freopen("in.txt", "r", stdin);
#endif //sxk
int n, m;
while(scanf("%d", &n) == 1){
ac.init();
for(int i = 1; i <= n; i++){
scanf("%s", vir[i]);
ac.insert(vir[i], i);
}
ac.build();
scanf("%s", buf);
ac.query(buf, n);
}
return 0;
}