The same 3940 to change the KMP to AC automatic machine on it, with a stack maintenance information is good.
#include <cstdio>
#include <cstring>
#include <iostream>
#define MAXN 100021
using namespace std;
int CH[MAXN][26],FAIL[MAXN],N,M,TOT,TOP,F[MAXN],VAL[MAXN],Q[MAXN*2],MX[MAXN];
Char ST[MAXN*2],SS[MAXN],SZ[MAXN];
void Insert (char* s) {
int rt=0,len=strlen (s);
for (int c,i=0;i<len;i++) {
c=s[i]-' a ';
if (!ch[rt][c]) Ch[rt][c]=++tot;
RT=CH[RT][C];
}
Val[rt]=len;
}
void make () {
int l=0,r=1;
while (l<r) {
int u=q[l++];;
for (int i=0;i<26;i++) {
if (Ch[u][i]) fail[ch[u][i]]= u==0? 0:ch[fail[u]][i],q[r++]=ch[u][i];
else ch[u][i]= u==0? 0:ch[fail[u]][i];
}
Mx[u]=max (Val[u],val[fail[u]]);
}
int main () {
scanf ("%s%d", ss,&m);
int Len=strlen (ss), rt=0;
while (m--) {
scanf ("%s", SZ);
Insert (SZ);
char c;
Make ();
for (int i=0;i<len;i++) {
st[++top]=c=ss[i];
RT=F[TOP-1];
rt=ch[rt][c-' a '];
F[top]=rt;
if (Mx[rt]) top-=mx[rt];
}
for (int i=1;i<=top;i++) printf ("%c", St[i]);
return 0;
}