题面
https://www.luogu.org/problem/P3121
题解
// luogu-judger-enable-o2 #include<cstdio> #include<iostream> #include<cstring> #include<queue> #define ri register int #define N 100050 using namespace std; char t[N]; char s[N]; int n; struct acautomato{ int ch[N][26]; int nex[N],cnt[N],last[N]; int tot; int pre[N]; char ans[N]; int ton[N],book[N]; void insert() { int now=0; int l=strlen(s+1); for (ri i=1;i<=l;i++) { int c=s[i]-'a'; if (!ch[now][c]) ch[now][c]=++tot; now=ch[now][c]; } cnt[now]=l; } void getfail() { queue<int> q; while (!q.empty()) q.pop(); for (ri c=0;c<26;c++) if (ch[0][c]) { if (cnt[ch[0][c]]) last[ch[0][c]]=cnt[ch[0][c]]; else last[ch[0][c]]=0; q.push(ch[0][c]); } while (!q.empty()) { int x=q.front(); q.pop(); for (ri c=0;c<26;c++) { int y=ch[x][c]; if (!y) ch[x][c]=ch[nex[x]][c]; else { nex[y]=ch[nex[x]][c]; if (cnt[y]) last[y]=cnt[y]; else last[y]=last[nex[y]]; q.push(y); } } } } void dp() { int now=0; int l=strlen(t+1); for (ri i=1;i<=l+1;i++) pre[i]=i-1; for (ri i=1;i<=l;i++) { now=ch[now][t[i]-'a']; book[i]=now; if (last[now]) { int j=i,ll=1; while (ll<last[now]) j=pre[j],ll++; pre[i+1]=pre[j]; now=book[pre[j]]; } } int p=pre[l+1],cnt=0; while (p) { ans[++cnt]=t[p]; p=pre[p]; } for (ri i=cnt;i>=1;i--) cout<<ans[i]; cout<<endl; } } trie; int main(){ scanf("%s",t+1); scanf("%d",&n); for (ri i=1;i<=n;i++) { scanf("%s",s+1); trie.insert(); } trie.getfail(); trie.dp(); }