题解 CF1203D2 【Remove the Substring (hard version)】

题目链接

Solution CF1203D

题目大意:给定两个字符串\(s\),\(t\), \(t\)\(s\)的子序列,问最长可以在\(s\)里面删掉多长的连续子序列使得\(t\)仍为\(s\)的子序列

贪心


分析:

假如我们\(t\)的一个前缀要匹配\(s\)的话,显然尽可能往前匹配,这样可以使得答案尽量大,后缀同理

我们用\(suf[i]\)表示\(t[1\dots i]\)可以匹配\(s\)前缀的最前的位置,\(suf[i]\)表示\(t[i \dots |t|]\)可以匹配\(s\)后缀的最后的位置

我们枚举所有\(t\)的位置\(i\),当\(pre[i] < suf[i + 1]\)时,\(suf[i + 1] - pre[i] - 1\)可以成为答案,取个最大值即可

CCF毒瘤程序

#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 2e5 + 100;
char s[maxn],t[maxn];
int slen,tlen,ans,pre[maxn],suf[maxn];
int main(){
    scanf("%s",s + 1);
    scanf("%s",t + 1);
    slen = strlen(s + 1);
    tlen = strlen(t + 1);
    for(int i = 1;i <= tlen;i++){
        pre[i] = pre[i - 1] + 1;
        while(pre[i] <= slen && s[pre[i]] != t[i])pre[i]++;     
    }
    suf[tlen + 1] = slen + 1;
    for(int i = tlen;i >= 1;i--){
        suf[i] = suf[i + 1] - 1;
        while(suf[i] >= 1 && s[suf[i]] != t[i])suf[i]--;
    }
    for(int i = 0;i <= tlen;i++)
        if(pre[i] < suf[i + 1])ans = max(ans,suf[i + 1] - pre[i] - 1);
    printf("%d\n",ans);
    return 0-0;
}

猜你喜欢

转载自www.cnblogs.com/colazcy/p/11737255.html