这是一道个人感觉很难的区间DP。
这道题,需要用两次DP。第一次是假设A字符串的每个字符都与B字符串的字符不同,然后用DP的思想,求将A转换成B所需的次数。第二次,因为某些A串中的字符与B字符串对应的位置相同,所以又存在减少次数的可能,这里又会再次用DP计算。
代码(G++):
#include <cstdlib>
#include <iostream>
#define MAX 105
//#define LOCAL
using namespace std;
char s1[MAX],s2[MAX];
int dp[MAX][MAX],ans[MAX];
int main(int argc, char *argv[])
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
while(scanf("%s%s",s1,s2)!=EOF) //EOF不可少,否则TLE
{
int i,j,k,len;
len=strlen(s1);
memset(dp,0,sizeof(dp));
for(i=0;i<len;i++)
{
for(j=i;j>=0;j--)
{
dp[j][i]=dp[j+1][i]+1;
for(k=j+1;k<=i;k++)
{
if(s2[j]==s2[k]) dp[j][i]<?=(dp[j+1][k] + (k+1<=i?dp[k+1][i]:0) );
}
}
}
for(i=0;i<len;i++) ans[i+1]=dp[0][i];//ans数组从1开始记录,因为可以避免当s1[0]==s2[0],出现ans[0]=ans[-1]的情况
for(i=0;i<len;i++)
{
if(s1[i]==s2[i]) ans[i+1]=ans[i];
else{
for(k=0;k<i;k++) ans[i+1]<?=ans[k+1]+dp[k+1][i];
}
}
printf("%d\n",ans[len]);
}
system("PAUSE");
return EXIT_SUCCESS;
}
题目( http://acm.hdu.edu.cn/showproblem.php?pid=2476):
String painter
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
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.
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