NOIP 模拟 $79; m s$

题解 (by;zjvarphi)

(dp_{i,j}) 表示第一个串前 (i) 个字符的后缀匹配上了第二个串长度为 (j) 的前缀需要最少删多少。

转移的时候需要讨论一下当前这个字符删不删:

[egin{cases} dp_{i+1,j}=dp_{i,j} ( ext{删掉i})\ dp_{i+1,trans(j,S_i)} ( ext{不删i}) end{cases} ]

其中 (trans(j,S_i)) 表示在 kmp 意义下的 next 的数组中下一位可以匹配上 (S_{i+1}) 的最长的一段。

卡空间,不要开 intshort 即可,还可以开个动态数组,或者把第一维滚动掉。

Code
#include<bits/stdc++.h>
#define ri signed
#define pd(i) ++i
#define bq(i) --i
#define func(x) std::function<x>
namespace IO{
    char buf[1<<21],*p1=buf,*p2=buf;
    #define gc() p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?(-1):*p1++
    #define debug1(x) std::cerr << #x"=" << x << ' '
    #define debug2(x) std::cerr << #x"=" << x << std::endl
    #define Debug(x) assert(x)
    struct nanfeng_stream{
        template<typename T>inline nanfeng_stream &operator>>(T &x) {
            bool f=false;x=0;char ch=gc();
            while(!isdigit(ch)) f|=ch=='-',ch=gc();
            while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=gc();
            return x=f?-x:x,*this;
        }
    }cin;
}
using IO::cin;
namespace nanfeng{
    #define FI FILE *IN
    #define FO FILE *OUT
    template<typename T>inline T cmax(T x,T y) {return x>y?x:y;}
    template<typename T>inline T cmin(T x,T y) {return x>y?y:x;}
    static const int N=8e3+7;
    short *dp[N],nxt[N],n,m,cur;
    char s1[N],s2[N];
    inline int main() {
        FI=freopen("s.in","r",stdin);
        FO=freopen("s.out","w",stdout);
        scanf("%s%s",s1+1,s2+1);
        n=strlen(s1+1),m=strlen(s2+1);
        nxt[0]=-1;
        for (ri i(2),j=0;i<=m;pd(i)) {
            while(j&&s2[i]!=s2[j+1]) j=nxt[j];
            if (s2[i]==s2[j+1]) ++j;
            nxt[i]=j;
        }
        for (ri i(0);i<=n;pd(i)) {
            dp[i]=new short[m+5];
            for (ri j(0);j<m+5;pd(j)) dp[i][j]=32222;
        }
        dp[0][0]=0;
        for (ri i(0);i<n;pd(i))
            for (ri j(0);j<m&&j<=i;pd(j)) {
                int cur=j;
                while((~cur)&&s1[i+1]!=s2[cur+1]) cur=nxt[cur];
                dp[i+1][cur+1]=cmin(dp[i][j],dp[i+1][cur+1]);
                dp[i+1][j]=cmin(short(dp[i][j]+1),dp[i+1][j]);
            }
        short ans=32222;
        for (ri i(0);i<m;pd(i)) ans=cmin(ans,dp[n][i]);
        printf("%d
",(int)ans); 
        return 0;
    }
}
int main() {return nanfeng::main();}
原文地址:https://www.cnblogs.com/nanfeng-blog/p/15419748.html