hdu2222 Keywords Search (AC自动机)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222
AC自动机板子题
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 1000010;
int T, n, rt = 0, tot = 0;
ll ans = 0;
struct Node{
int son[30], sz, fail;
}t[maxn];
char s[maxn];
void insert(){
int p = rt;
int len = strlen(s);
for(int i = 0 ; i < len ; ++i){
if(!t[p].son[s[i] - 'a']){
t[p].son[s[i] - 'a'] = ++tot;
}
p = t[p].son[s[i] - 'a'];
}
++t[p].sz;
}
queue<int> q;
void build(){
t[rt].fail = rt;
for(int i = 0 ; i <= 25 ; ++i){
if(t[rt].son[i]) q.push(t[rt].son[i]);
}
while(!q.empty()){
int u = q.front(); q.pop();
for(int i = 0 ; i <= 25 ; ++i){
if(t[u].son[i]){
t[t[u].son[i]].fail = t[t[u].fail].son[i];
q.push(t[u].son[i]);
} else{
t[u].son[i] = t[t[u].fail].son[i];
}
}
}
}
void query(){
int p = rt;
int len = strlen(s);
for(int i = 0 ; i < len ; ++i){
p = t[p].son[s[i] - 'a'];
for(int j = p ; j && ~t[j].sz ; j = t[j].fail) ans += t[j].sz, t[j].sz = -1;
}
}
ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }
int main(){
T = read();
while(T--){
memset(t, 0, sizeof(t));
tot = 0, ans = 0;
n = read();
for(int i = 1 ; i <= n ; ++i){
scanf("%s", s);
insert();
}
build();
scanf("%s", s);
query();
printf("%lld\n", ans);
}
return 0;
}