There are two strings A and B with equal length. Both strings are made up of lower case letters. Now you have a powerful string painter. With the help of the painter, you can change a segment of characters of a string to any other character you want. That is, after using the painter, the segment is made up of only one kind of character. Now your task is to change A to B using string painter. What’s the minimum number of operations?
Input
Input contains multiple cases. Each case consists of two lines:
The first line contains string A.
The second line contains string B.
The length of both strings will not be greater than 100.
Output
A single line contains one integer representing the answer.
Sample Input
zzzzzfzzzzz
abcdefedcba
abababababab
cdcdcdcdcdcd
Sample Output
6
7
最近在专心研究区间dp,被这道题卡了一天,今天终于AC了;
快乐的写一篇博客,巩固一下学到的东西
1.为什么这是区间dp
答:因为粉刷的是区间,是以区间为研究对象。
2.怎么构思?
答:因为有两个字符串,如果一开始就dp操作,会特别的复杂,所以我们考虑先把a串看作是空白串,利用区间dp求出将空白串刷成b串的最优解
初始化:
for(int i=0; i<n; i++)
{
if(b[i]==b[i+1]) dp[i][i+1]=1;//如果相邻的字母相同就只刷一下
else dp[i][i+1]=2;//如果不同就刷两下
dp[i][i]=1; //单个的就刷一下
}
动态方程:
for(int i=2; i<n; i++)//距离
{
for(int j=0; j+i<=n-1; j++)//起点
{
int p=j+i;//终点
dp[j][p]=min(dp[j+1][p]+1,dp[j][p-1]+1);//例如字符串 abc 我们可以看做是先刷的a又刷的bc,或者是先ab再c,所以得出初始化方程。
for(int k=j+1; k<=p; k++)//探索中间的点,这里+1和等于号的取舍一定要用特殊案例测试,这里是成败关键
{
if(b[j]==b[k])不相等的话就没必要操作了,比如说abc
dp[j][p]=min(dp[j][p],dp[j+1][k]+dp[k+1][p]);但如果相等,例如abca->aaaa->abba->abca与abc是一样的,所以可以写成dp[j+1][k],然后再加上后面的就ok!
}
}
}
后面的就更关键了
我们求的是a串变b串,而上面的是空白串变b串
所以我们搞一手ans[N]一维数组,表示刷前i个的最优解
初始化
for(int i=0; i<n ;i++)
ans[i]=dp[0][i]; //初始化成空白串的次数
for(int i=0; i<n; i++)
{
if(a[i]==b[i])
{
if(i==0)
ans[i]=0;//第一项如果就相同的话,就直接从第二项刷,不管他了,所以是0!
else
ans[i]=ans[i-1]; //其他的话,就是前i-1的了
}
else
for(int j=0; j<i; j++)//此处高能,为什么还要遍历中间呢?!原因其实很简单,因为ans【i】是被初始换成空白串到b串的次数,虽然此时在i处,ab两串不同,但是不妨碍i前的点两串存在相同的点啊,如果存在的话,不进行以下操作,不就让ansi偏大了吗?所以以下遍历中间节点,就是找是否存在在零到i之间有ab两串相同的点
ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
}
printf("%d\n",ans[n-1]);
AC
#include
#include
#include
using namespace std;
#define N 150
char a[N];
char b[N];
int dp[N][N];
int n;
int ans[N];
int main()
{
while(scanf("%s",a)!=EOF)
{
scanf("%s",b);
n=strlen(b);
memset(dp,0,sizeof(dp));
for(int i=0; i<n; i++)
{
if(b[i]==b[i+1]) dp[i][i+1]=1;//如果相邻的字母相同就只刷一下
else dp[i][i+1]=2;//如果不同就刷两下
dp[i][i]=1; //单个单个的刷
}
for(int i=2; i<n; i++)//距离
{
for(int j=0; j+i<=n-1; j++)//起点
{
int p=j+i;//终点
dp[j][p]=min(dp[j+1][p]+1,dp[j][p-1]+1);
for(int k=j+1; k<=p; k++)
{
if(b[j]==b[k])
dp[j][p]=min(dp[j][p],dp[j+1][k]+dp[k+1][p]);
}
}
}
for(int i=0; i<n ;i++)
ans[i]=dp[0][i];
for(int i=0; i<n; i++)
{
if(a[i]==b[i])
{
if(i==0)
ans[i]=0;
else
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[n-1]);
}
return 0;
}
不喜勿喷哦!= =