HDU 2476 String painter(区间DP)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2476


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


题意:

给定两个字符串,第一个是初始串,第二个是目标串,问你把初始串变到目标串最少需要多少步!

PS:

1:假设初始串是空串,然后进行区间dp,dp[i][j]表示区间[i, j]变到与目标串相同最少需要的步数,有:dp[i][j]=dp[i+1][j]+1;

2:如果s2[i] == s2[k],有:dp[i][j] = min(dp[i][j], dp[i+1][k]+dp[k+1][j])。


代码如下:

#include <cstdio>
#include <cstring>
#define maxn 117
int MIN(int a, int b)
{
    if(a < b)
        return a;
    return b;
}
int main()
{
    int dp[maxn][maxn];//区间[i, j]的最少次数
    int a[maxn];
    char s1[maxn], s2[maxn];
    while(~scanf("%s",s1))
    {
        scanf("%s",s2);
        int len = strlen(s1);
        memset(dp,0,sizeof(dp));
        //求区间[i,j]最少次数;
        for(int j = 0; j < len; j++)
        {
            for(int i = j; i >= 0; i--)
            {
                dp[i][j] = dp[i+1][j]+1;//一个一个的刷
                for(int k = i+1; k <= j; k++)
                {
                    if(s2[i] == s2[k])
                    {
                        dp[i][j] = MIN(dp[i][j], dp[i+1][k]+dp[k+1][j]);//最优解
                    }
                }
            }
            a[j] = dp[0][j];
        }
        for(int i = 0; i < len; i++)
        {
            if(s1[i]==s2[i])
            {
                a[i] = a[i-1];
                //如果对应位置相等,可以不刷
                continue;
            }
            for(int j = 0; j < i; j++)
            {
                a[i] = MIN(a[i],a[j]+dp[j+1][i]);//最优解
            }
        }
        printf("%d\n",a[len-1]);
    }
    return 0;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值