洛谷P4824 [USACO15FEB]Censoring S

题链

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

#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;
}
posted @ 2021-03-25 13:39  棉被sunlie  阅读(38)  评论(0)    收藏  举报