前置知识:AC 自动机
又水一道 提高+/省选−。
题意分析
在文本串 $t$ 中查找模式串 $s_1,s_2,s_3,\cdots,s_n$,从 $t$ 中删除所有可能查找到的 $s_i$ 并输出删除之后的 $t$。
多字符串匹配问题,一眼 AC 自动机。
但是这道题目唯一可能有困惑的地方就是:有可能删除之后的两段会合并产生新的 $s_i$。没错就是这东西害我模拟赛痛失 40 分。
但其实我们仅仅需要让查询函数中的指针 $p$ 回退到匹配到的 $s_i$ 的起点的前一个节点即可。
在这之后仍然继续访问 $t$ 的下一个节点,也就相当于拼接到了一起。
但是,请注意,一旦匹配到了模式串,就应当立即删除,不能等待扫完一遍之后一起删除。
AC 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
constexpr const int T=1e5,S=1e5;
char t[T+1],s[S+1];
struct trie{
struct node{
int m[26];
int len,fail;
}t[S+1];
void insert(char *s){
int p=0;
for(int i=0;s[i];i++){
if(!t[p].m[s[i]-'a']){
static int top;
t[p].m[s[i]-'a']=++top;
}
p=t[p].m[s[i]-'a'];
}int len=strlen(s);
t[p].len = max(t[p].len,len);
}//构造AC 自动机/Trie图
void build(){
queue<int>q;
for(int i=0;i<26;i++){
if(t[0].m[i]){
q.push(t[0].m[i]);
}
}
while(q.size()){
int p=q.front();q.pop();
for(int i=0;i<26;i++){
if(t[p].m[i]){
t[t[p].m[i]].fail = t[t[p].fail].m[i];
q.push(t[p].m[i]);
}else{
t[p].m[i] = t[t[p].fail].m[i];
}
}
}
}
void query(char *s){
int p=0;
//两个栈(stack过慢)
vector<int>path;
vector<char>ans;
for(int i=0;s[i];i++){
p=t[p].m[s[i]-'a'];
path.push_back(p);
ans.push_back(s[i]);
if(t[p].len){
//回退
path.resize(path.size()-t[p].len);
ans.resize(ans.size()-t[p].len);
p=path.back();
}
}
for(char &i:ans){
putchar(i);
}putchar(10);
}
}trie;
int main(){
/*freopen("test.in","r",stdin);
freopen("test.out","w",stdout);*/
scanf("%s",t);
int n;
scanf("%d",&n);
while(n--){
scanf("%s",s);
trie.insert(s);
}trie.build();
trie.query(t);
/*fclose(stdin);
fclose(stdout);*/
return 0;
}