记录一个当前串长为i时,在AC自动机上的哪个节点。找到匹配串时,直接O(1)跳到那个节点就行了。
/* Pigonometry */
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000005, maxq = maxn;
int n, pos[maxn], q[maxq];
char s[maxn], str[maxn], ans[maxn];
int son[maxn][26], fail[maxn], acmcnt, flag[maxn];
inline void insert() {
int now = 0, len = strlen(str);
for(int i = 0; i < len; i++) {
int &pos = son[now][str[i] - 'a'];
if(!pos) pos = ++acmcnt;
now = pos;
}
flag[now] = max(flag[now], len);
}
inline void getfail() {
int h = 0, t = 0;
for(int i = 0; i < 26; i++) if(son[0][i]) q[t++] = son[0][i];
while(h != t) {
int u = q[h++];
for(int i = 0; i < 26; i++)
if(!son[u][i]) son[u][i] = son[fail[u]][i];
else {
fail[q[t++] = son[u][i]] = son[fail[u]][i];
flag[son[u][i]] = max(flag[son[u][i]], flag[fail[son[u][i]]]);
}
}
}
int main() {
scanf("%s%d", s, &n);
for(int i = 1; i <= n; i++) {
scanf("%s", str);
insert();
}
getfail();
int now = 0, tot = 0, len = strlen(s);
for(int i = 0; i < len; i++) {
now = son[now][s[i] - 'a']; ans[tot] = s[i];
pos[tot] = now; tot++;
if(flag[now]) {
tot -= flag[now];
now = pos[tot - 1];
}
}
ans[tot] = '\0';
printf("%s\n", ans);
return 0;
}