【BZOJ3942】【Usaco2015 Feb】Censoring KMP

来源:互联网 发布:诺基亚c1 02java软件 编辑:程序博客网 时间:2024/05/12 17:53

链接:

#include <stdio.h>int main(){    puts("转载请注明出处[vmurder]谢谢");    puts("网址:blog.csdn.net/vmurder/article/details/44959895");}

我猜的题意(已经AC):

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

题解:

KMP 判断当前U串最后一个字母加进来以后有多少字符匹配。

代码:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define N 1001000using namespace std;char s[N],t[N];int n,m,pre[N],fix;int f[N],stk[N],top;int main(){    freopen("test.in","r",stdin);    int i;    scanf("%s%s",s+1,t+1);    m=strlen(s+1),n=strlen(t+1);    for(fix=0,i=2;i<=n;i++)    {        while(fix&&t[fix+1]!=t[i])fix=pre[fix];        if(t[fix+1]==t[i])fix++;        pre[i]=fix;    }    for(i=1;i<=m;i++)    {        fix=f[stk[top]];        while(fix&&t[fix+1]!=s[i])fix=pre[fix];        if(t[fix+1]==s[i])fix++;        if(fix==n)top-=(n-1);        else f[i]=fix,stk[++top]=i;    }    for(i=1;i<=top;i++)printf("%c",s[stk[i]]);    return 0;}
0 0