【KMP】洛谷 P4824 Censoring S
2021-03-25 13:39:00 # ACM

题链

求出模式串的前缀数组后,一个个读入文本串字符,遇到与模式串相同的字串(前缀值与模式串长度$len$相等),弹出栈顶$len$个前缀函数值,相当于消去这$len$个长度的字符的影响,以栈的形式存储答案与文本串的前缀数组

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
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#pragma GCC optimize("O2")
using namespace std;
#define LL long long
#define ll long long
#define ULL unsigned long long
#define ls rt<<1
#define rs rt<<1|1
#define one first
#define two second
#define MS 1000009
#define INF 1e18
#define mod 99999997
#define Pi acos(-1.0)
#define Pair pair<LL,LL>
#define eps 1e-9

LL n,m,k;
char s[MS];
char e[MS];
LL ac[MS];
LL kpe[MS];
LL kps[MS];
LL hs,he,tac;

void kmp_e(){
he = strlen(e);
kpe[0] = 0;
for(int i=1;i<he;i++){
int j=kpe[i-1];
while(j>0 && e[i] != e[j]) j = kpe[j-1];
if(e[i] == e[j]) j++;
kpe[i] = j;
}
}

int main(){
ios::sync_with_stdio(false);
cin >> s; // 文本串
cin >> e; // 模式串
kmp_e();
hs = strlen(s);
tac = 0; // 栈指针

for(int i=0,j=0;i<hs;i++){
while(j>0 && s[i] != e[j]) j = kpe[j-1];
if(s[i] == e[j]) j++;
kps[i] = j; // 前缀函数值
/******************************************/
ac[tac] = i; // 存储文本串位置i
if(j == he){ // 若相符
tac -= he; // 栈顶弹出 长度与模式串同等数量
j = kps[ac[tac]]; // 跳到上次位置
}
tac++;
/******************************************/
}
for(int i=0;i<tac;i++){
cout << s[ac[i]];
}
cout << endl;


return 0;
}
Prev
2021-03-25 13:39:00 # ACM
Next