AC自动机(模板)

时间:2023-03-08 22:48:39
 #include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <queue> using namespace std; int n, ans[ + ];
char str[][ + ]; struct AcAutomaton{
static const int N = + ;
static const int C = ; int size;
int ch[N][C], fail[N], num[N], end[N]; AcAutomaton(){
size = ;
} int idx(char c){
return c - 'a';
} void insert(char *buf, int k){
int cur = , len = strlen(buf); for(int i = ; i < len; ++ i){
int x = idx(buf[i]); if(!ch[cur][x])
ch[cur][x] = size ++;
cur = ch[cur][x];
} end[cur] ++; num[cur] = k;
} void build(){
queue <int> q;
fail[] = ; for(int i = ; i < C; ++ i){
if(!ch[][i]) ch[][i] = ;
else{
fail[ch[][i]] = ;
q.push(ch[][i]);
}
} while(!q.empty()){
int x = q.front(); q.pop(); for(int i = ; i < ; ++ i){
if(!ch[x][i]) ch[x][i] = ch[fail[x]][i];
else{
fail[ch[x][i]] = ch[fail[x]][i];
q.push(ch[x][i]);
}
}
}
} void find(char* buf){
int cur = , len = strlen(buf); for(int i = ; i < len; ++ i){
int x = idx(buf[i]); cur = ch[cur][x]; int tmp = cur;
while(tmp){
if(end[tmp])
ans[num[tmp]] += end[tmp];
tmp = fail[tmp];
}
}
}
}ac; int main(){
#ifndef ONLINE_JUDGE
freopen("ACautomata.in", "r", stdin);
freopen("ACautomata.out", "w", stdout);
#endif scanf("%d", &n);
for(int i = ; i <= n; ++ i){
scanf("%s", str[i]);
ac.insert(str[i], i);
}
ac.build();
scanf("%s", str[n+]);
ac.find(str[n+]); for(int i = ; i <= n; ++ i){
int tp = strlen(str[i]);
for(int j = ; j < tp; ++ j)
printf("%c", str[i][j]);
printf(" %d\n", ans[i]);
} #ifndef ONLINE_JUDGE
fclose(stdin); fclose(stdout);
#endif return ;
}

AcAutomaton