原題地址
String painter
The first line contains string A.
The second line contains string B.
The length of both strings will not be greater than 100.
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
char str1[111],str2[111];
int dp[111][111];
int ans[111];
int main()
{
while(~scanf("%s",&str1))
{
scanf("%s",&str2);
int i,j,l;
l=strlen(str1);
memset(dp,0,sizeof(dp));
for(j=0;j<l;j++)
{
for(i=j;i>=0;i--)
{
dp[i][j]=dp[i+1][j]+1;
for(int p=i+1;p<=j;p++)
{
if(str2[i]==str2[p])
dp[i][j] = min(dp[i][j],(dp[i+1][p]+dp[p+1][j]));
}
}
}
for(int i=0;i<l;i++)
{
ans[i]=dp[0][i];
}
for(int i=0;i<l;i++)
{
if(str1[i]==str2[i])
{
ans[i]=ans[i-1];
}
else
{
for(int j=0;j<i;j++)
{
ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
}
}
}
printf("%d\n",ans[l-1]);
}
return 0;
}