AC自动机
saxiy
·
·
个人记录
新写的AC自动机(P3121,不是板子题)
#pragma GCC optimize("Ofast,fast-math,unroll-loops")
#include <bits/stdc++.h>
#define N 100005
using namespace std;
int n, stid[N], top;
char str[N], msc[N], stc[N];
int trie[N][26], ed[N], p[N], cnt = 2;
void insert(const char* str) {
int now = 1, len = strlen(str);
for(int i = 0;i < len;i++) {
int ch = str[i] - 'a';
if(!trie[now][ch]) trie[now][ch] = cnt++;
now = trie[now][ch];
}
ed[now] = len;
}
void pre() {
for(int ch = 0;ch < 26;ch++)
trie[0][ch] = 1;
queue <int> q;
q.push(1);
while(q.size()) {
int now = q.front(); q.pop();
for(int ch = 0;ch < 26;ch++) {
if(trie[now][ch]) {
q.push(trie[now][ch]);
p[trie[now][ch]] = trie[p[now]][ch];
} else trie[now][ch] = trie[p[now]][ch];
}
}
}
void AC_run(const char* str) {
int now = 1, len = strlen(str);
for(int i = 0;i < len;i++) {
stid[top] = now;
int ch = (stc[top++] = str[i]) - 'a';
now = trie[now][ch];
if(ed[now])
now = stid[top -= ed[now]];
}
stc[top] = '\0';
}
int main() {
scanf("%s%d", str, &n);
while(n--) {
scanf("%s", msc);
insert(msc);
}
pre();
AC_run(str);
puts(stc);
return 0;
}