我们先考虑从一个空白串变成\(B\),这样的话用区间dp,区间dp,设\(f[l][r]\)表示区间\((l,r)\)的最小次数,当\(l==r\)时为\(1\),当\(s[l]==s[r]\)时为\(min(f[l][r-1],f[l+1][r])\),否则枚举断点\(k\),为\(min(f[l][k]+f[k+1][r])\)
然后考虑从\(A\)变成\(B\),设\(dp[i]\)表示\(A\)的前\(i\)个字母变成\(B\)的最小次数,一开始先设成\(f[1][i]\),如果\(A[i]==B[i]\)那么设为\(dp[i-1]\),然后枚举断点\(k\),则\(dp[i]=min\{dp[k]+f[k+1][i]\}\)//minamoto#include#define R register#define inf 0x3f3f3f3f#define min(x,y) ((x)<(y)?(x):(y))#define fp(i,a,b) for(R int i=a,I=b+1;i I;--i)#define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v)using namespace std;const int N=105;int f[N][N],dp[N],n;char A[N],B[N];void solve(){ n=strlen(A+1),memset(f,0x3f,sizeof(f)),memset(dp,0x3f,sizeof(dp)); fp(i,0,n)f[i][i]=1; fp(l,1,n-1)fp(i,1,n-l){ if(B[i]==B[i+l])f[i][i+l]=min(f[i+1][i+l],f[i][i+l-1]); else fp(k,i,i+l-1)f[i][i+l]=min(f[i][i+l],f[i][k]+f[k+1][i+l]); }dp[1]=A[1]==B[1]?0:1; fp(i,2,n){ dp[i]=f[1][i];if(A[i]==B[i])dp[i]=min(dp[i],dp[i-1]); else fp(j,1,i-1)dp[i]=min(dp[i],dp[j]+f[j+1][i]); }printf("%d\n",dp[n]);}int main(){// freopen("testdata.in","r",stdin); while(~scanf("%s%s",A+1,B+1))solve(); return 0;}