您的位置:首页 > Web前端

[BZOJ]3942: [Usaco2015 Feb]Censoring KMP

2017-09-15 18:48 295 查看
Description

有一个S串和一个T串,长度均小于1,000,000,设当前串为U串,然后从前往后枚举S串一个字符一个字符往U串里添加,若U串后缀为T,则去掉这个后缀继续流程。

题解:

用一个数组保存当前的答案字符串,另一个数组保存每个字符匹配到哪个位,匹配过程用KMP加速。

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1000010;
char s[maxn],t[maxn],str[maxn];
int pp[maxn],len=0;
int next[maxn];
int main()
{
scanf("%s%s",s+1,t+1);
next[1]=0;int p=0,lt=strlen(t+1),ls=strlen(s+1);
for(int i=2;i<=lt;i++)
{
while(p&&t[p+1]!=t[i])p=next[p];
if(t[p+1]==t[i])p++;
next[i]=p;
}
p=0;
int lp=0;
for(int i=1;i<=ls;i++)
{
while(p&&t[p+1]!=s[i])p=next[p];
if(t[p+1]==s[i])p++;
str[++len]=s[i];
pp[len]=p;
if(p==lt)
{
len-=lt;
p=pp[len];
}
}
for(int i=1;i<=len;i++)
printf("%c",str[i]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: