214人阅读 评论(0)

# String painter

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3530    Accepted Submission(s): 1640

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.

Output
A single line contains one integer representing the answer.

Sample Input
zzzzzfzzzzz
abcdefedcba
abababababab
cdcdcdcdcdcd

Sample Output
6
7

Source
2008 Asia Regional Chengdu

毫无疑问是区间dp,但是怎么写出表达式是一个很严肃的问题o(￣▽￣)do(￣▽￣)do(￣▽￣)d

由空串修改成第二串这个区间dp还是很好写的，个人觉得下面的那个转化才是神奇。
空串转化第二串，度娘给我的那个确实不错，但是我估计比较笨，想不到那种转化。
当然学习一下还是非常有必要的，说不定什么时候用上了呢。。

for(j = 0; j<len; j++)
{
for(i = j; i>=0; i--)//j为尾，i为头
{
dp[i][j] = dp[i+1][j]+1;//先每个单独刷
for(k = i+1; k<=j; k++)//i到j中间所有的刷法
{
if(s2[i]==s2[k])
dp[i][j] = min(dp[i][j],(dp[i+1][k]+dp[k+1][j]));//i与k相同，寻找i刷到k的最优方案
}
}
}  

 for(int len=2;len<=n;len++)
{
for(int l=0;l+len-1<n;l++)
{
int r=l+len-1;
if(s[l]==s[l+1])
dp[l][r]=dp[l+1][r];
else if(s[r]==s[r-1])
dp[l][r]=dp[l][r-1];
else if(s[l]==s[r])
{
dp[l][r]=dp[l+1][r-1]+1;
for(int k=1;k<r;k++)
if(s[l]==s[k])
dp[l][r]=min(dp[l][r],dp[l][k]+dp[k][r]-1);
}
for(int k=l;k<r;k++)
{
dp[l][r]=min(dp[l][r],dp[l][k]+dp[k+1][r]);
}
}
}

      for(int i=0;i<n;i++)
res[i]=dp[0][i];

for(int i=0;i<n;i++)
{
if(s[i]==s1[i])
{
if(i==0)
res[i]=0;
else
res[i]=res[i-1];
}
else
{
for(int j=0;j<i;j++)
res[i]=min(res[i],res[j]+dp[j+1][i]);
}
}

ans[i]代表的是[0,i]的最小转化步数。

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：10308次
• 积分：703
• 等级：
• 排名：千里之外
• 原创：56篇
• 转载：8篇
• 译文：0篇
• 评论：4条
阅读排行
评论排行
最新评论