HDU 2476 String painter 区间DP

来源:互联网 发布:小米笔记本12.5 知乎 编辑:程序博客网 时间:2024/05/16 11:29

String painter

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


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
zzzzzfzzzzzabcdefedcbaababababababcdcdcdcdcdcd
 

Sample Output
67
 

Source
2008 Asia Regional Chengdu
 

Recommend
lcy

    又是一道费脑DP。。。

    dp[i][j]表示将一个空白字符串的[i,j]区间刷为与str2的[i,j]区间相同所需要的最少次数。

    首先,我们能够知道dp[i][j]=dp[i+1][j]+1,因为假设str1为空串,因此每一个字符都需要刷新。

    然后我们考虑在什么情况下可以减少刷新的次数?如果存在多个相同的字符,那么我们就可以只刷一遍了,形式化以后,我们只考虑第i个字符与第k个字符是否相等,因为这种判断必定会蔓延到整个区间,当str2[i]==str2[k],那么我们有两种策略,要么把[i+1,k-1]这个区间刷完,然后分别刷i和k;要么首先刷k,并且刷k的时候顺便把i也刷了,然后再刷[i+1,k-1]。很明显第二种方案要好,因此dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j])。

    上面求解完成之后并没有完成,因为我们是假设str1为空串得到的最优解,事实上如果str1[i]==str2[i],那么i这个位置是不用刷的。我们首先让res[i]=dp[0][i],假设res中存放的就是最优解,那么当str1[[i]==str2[i]的时候,res[i]=res[i-1](如果i==0,res[i]=0);否则我们就需要找出一个最优解,由于我们已经知道了[0,i-1]的最优解,因此res[i]的最优解可以由res[k]和dp[k+1][i]得出,至于是哪一个k,我们就需要遍历一下。







/***********************功能:给出两个字符串,将一个转换成另一个,方法是将一段区间设置为同一个字符,问最少次数参数:两个字符串返回值:最少刷新次数***********************/#include <iostream>#include <stdio.h>#include <string.h>#define maxn 110using namespace std;char str1[maxn],str2[maxn];int dp[maxn][maxn];void get_dp(int n){    int i,j,k,len;    memset(dp,0,sizeof(dp));    for(len=1;len<=n;len++)    {        for(i=0;i<=n-len;i++)        {            j=i+len-1;            dp[i][j]=dp[i+1][j]+1;            for(k=i+1;k<=j;k++)            {                if(str2[i]==str2[k])                    dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);            }        }    }}int solve(int n){    get_dp(n);    int res[maxn];    int i,j;    for(i=0;i<n;i++)        res[i]=dp[0][i];    for(i=0;i<n;i++)    {        if(str1[i]==str2[i])        {            if(i==0)                res[i]=0;            res[i]=res[i-1];        }        else        {            for(j=0;j<=i-1;j++)                res[i]=min(res[i],res[j]+dp[j+1][i]);        }    }    return res[n-1];}int main(){    int len;    while(~scanf("%s%s",str1,str2))    {        len=strlen(str1);        printf("%d\n",solve(len));    }    return 0;}


0 0