码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 2476 String painter(区间DP啊)

时间:2015-08-30 21:24:31      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:hdu   dp   区间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;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU 2476 String painter(区间DP啊)

标签:hdu   dp   区间dp   

原文地址:http://blog.csdn.net/u012860063/article/details/48108647

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!