Aho板子
hdu2222
题意:t组数据,有n1e4个长度50的字符串,给了一个长度1e6模式串问模式串中有几个子串
代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define forn(i,n) for(int i=0;i<n;i++)
#define for1(i,n) for(int i=1;i<=n;i++)
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
const int maxn = 5e5+5;
int trie[maxn][26],id,cnt[maxn],fail[maxn];
queue<int>q;
class Aho{
public:
void init(){
memset(trie,0,sizeof(trie));
memset(cnt,0,sizeof(cnt));
memset(fail,0,sizeof(fail));
id = 0;
}
void insert(string s){
int len = s.size(),u = 0;
forn(i,len){
int x = s[i]-'a';
if(!trie[u][x]) trie[u][x] = ++id;
u = trie[u][x];
}
cnt[u]++;
}
void build(){
forn(i,26) if(trie[0][i]) q.push(trie[0][i]);
while(!q.empty()){
int u = q.front();q.pop();
forn(i,26){
if(trie[u][i]) fail[trie[u][i]] = trie[fail[u]][i],q.push(trie[u][i]);
else trie[u][i] = trie[fail[u]][i];
}
}
}
int find(string s){
int len = s.size(),u = 0,res = 0;
forn(i,len){
int x = s[i]-'a';
u = trie[u][x];
for(int j = u;j&&cnt[j]!=-1;j = fail[j]){
res+=cnt[j],cnt[j] = -1;
}
}
return res;
}
}aho;
int main(){
IO;
int t;cin>>t;
while(t--){
aho.init();
int n;cin>>n;
string s;forn(i,n){
cin>>s;
aho.insert(s);
}
aho.build();
cin>>s;
cout <<aho.find(s)<<'
';
}
return 0;
}