BZOJ3942: [Usaco2015 Feb]Censoring(KMP)

Description
Farmer John has purchased a subscription to Good Hooveskeeping magazine for his cows, so they have plenty of material to read while waiting around in the barn during milking sessions. Unfortunately, the latest issue contains a rather inappropriate article on how to cook the perfect steak, which FJ would rather his cows not see (clearly, the magazine is in need of better editorial oversight).

FJ has taken all of the text from the magazine to create the string S of length at most 10^6 characters. From this, he would like to remove occurrences of a substring T to censor the inappropriate content. To do this, Farmer John finds the first occurrence of T in S and deletes it. He then repeats the process again, deleting the first occurrence of T again, continuing until there are no more occurrences of T in S. Note that the deletion of one occurrence might create a new occurrence of T that didn’t exist before.

Please help FJ determine the final contents of S after censoring is complete

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

Input
The first line will contain S. The second line will contain T. The length of T will be at most that of S, and all characters of S and T will be lower-case alphabet characters (in the range a…z).
Output
The string S after all deletions are complete. It is guaranteed that S will not become empty during the deletion process.
Sample Input
whatthemomooofun

moo
Sample Output
whatthefun
HINT
Source
Silver

思路:
设为A,B字符串
f[i]数组的含义是B字符串前i个字符的最长公共前后缀。
再维护每次匹配到A的字符最多能匹配的B字符个数。
一边匹配一边加字符,匹配到了一整个字符串就删掉一个B字符串长度。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;
const int maxn = 1e6 + 7;
int len1,len2,len3;
int f[maxn],nex[maxn];
char s1[maxn],s2[maxn],s3[maxn];

void getf()
{
    for(int i = 2;i <= len1;i++)
    {
        int j = f[i - 1];
        while(j && s2[i] != s2[j + 1])
        {
            j = f[j];
        }
        f[i] = s2[i] == s2[j + 1] ? j + 1 : j;
    }
}

void check()
{
    int j = 0;
    for(int i = 1;i <= len1;i++)
    {
        j = nex[len3];
        s3[++len3] = s1[i];
        while(j && (s1[i] != s2[j + 1]))
        {
            j = f[j];
        }
        if(s1[i] == s2[j + 1])j++;
        nex[len3] = j;
        if(j == len2)
        {
            len3 -= len2;
        }
    }
}

int main()
{
    scanf("%s%s",s1 + 1,s2 + 1);
    len1 = (int)strlen(s1 + 1);len2 = (int)strlen(s2 + 1);len3 = 0;
    getf();
    check();
    for(int i = 1;i <= len3;i++)printf("%c",s3[i]);
    return 0;
}

发布了629 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/104084128