题解
多模匹配。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
struct Node{
Node* fail;
Node* next[26];
int cnt;
Node(){
fail = NULL;
cnt = 0;
memset(next, 0, sizeof(next));
}
};
struct AC_automation{
Node* root;
AC_automation(){
root = new Node();
}
void insert(string s){
Node* p = root;
for(int i = 0; i < s.length(); ++i){
int id = s[i] - 'a';
if(!p->next[id]) p->next[id] = new Node();
p = p->next[id];
}
p->cnt++;
}
void build_fail(){
root->fail = NULL;
queue<Node*> Q;
Q.push(root);
while(!Q.empty()){
Node* cur = Q.front(); Q.pop();
for(int i = 0; i < 26; ++i){
if(cur->next[i]){
if(cur == root){
cur->next[i]->fail = root;
}else{
Node* p = cur->fail;
while(p){
if(p->next[i]){
cur->next[i]->fail = p->next[i];
break;
}
p = p->fail;
}
if(p == NULL){
cur->next[i]->fail = root;
}
}
Q.push(cur->next[i]);
}
}
}
}
int search(string text){
int cnt = 0;
Node* p = root;
for(int i = 0; i < text.length(); ++i){
int id = text[i] - 'a';
while(p->next[id] == NULL && p != root) p = p->fail;
p = p->next[id];
if(p == NULL) p = root;
Node* tmp = p;
while(tmp != root && tmp->cnt != -1){
cnt += tmp->cnt;
tmp->cnt = -1;
tmp = tmp->fail;
}
}
return cnt;
}
void clear(){
clear(root);
}
void clear(Node* p){
if(p){
for(int i = 0; i < 26; ++i){
if(p->next[i]) clear(p->next[i]);
}
delete p;
}
}
};
int main(){
#ifdef EXMY
freopen("data.in", "r", stdin);
#endif // EXMY
ios::sync_with_stdio(false);
int n, t;
string s;
cin >> t;
while(t--){
AC_automation ac;
cin >> n;
for(int i = 0; i < n; ++i){
cin >> s;
ac.insert(s);
}
ac.build_fail();
cin >> s;
cout << ac.search(s) << endl;
}
return 0;
}