hdu2476 String painter (区间DP)

来源:互联网 发布:网络语言我都快长草了 编辑:程序博客网 时间:2024/06/05 18:04

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

题意:

给出两个串s1和s2,一次只能将一个区间刷一次,问最少几次能让s1=s2

例如zzzzzfzzzzz,长度为11,我们就将下标看做0~10

先将0~10刷一次,变成aaaaaaaaaaa

1~9刷一次,abbbbbbbbba

2~8:abcccccccba

3~7:abcdddddcba

4~6:abcdeeedcab

5:abcdefedcab

这样就6次,变成了s2串了

第二个样例也一样

0

先将0~10刷一次,变成ccccccccccb

1~9刷一次,cdddddddddcb

2~8:cdcccccccdcb

3~7:cdcdddddcdcb

4~6:cdcdcccdcdcb

5:cdcdcdcdcdcb

最后竟串尾未处理的刷一次

就变成了串2cdcdcdcdcdcd

所以一共7次

思路:将字符串变相等,先将两个字符串所有字符串都不对应相等的情况考虑;然后再判断对应相等的情况,两次都需要区间DP;
代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int main(){    char c1[105],c2[105];    int dp[105][105];  //dp[i][j]为i~j的刷法      int ans[105];    while(~scanf("%s",c1))    {        scanf("%s",c2);        int len1=strlen(c1);        int len2=strlen(c2);        memset(dp,0,sizeof(dp));        memset(ans,0,sizeof(ans));        for(int i=0;i<len1;i++) //考虑字符串全对应不相等;            for(int j=i;j>=0;j--)            {                dp[j][i]=dp[j+1][i]+1;                for(int k=j+1;k<=i;k++)                {                    if(c2[j]==c2[k])                        dp[j][i]=min(dp[j][i],dp[j+1][k]+dp[k+1][i]); //j与k相同,寻找j刷到k的最优方案                  }            }        for(int i=0;i<len1;i++)            ans[i]=dp[0][i];        for(int i=0;i<len1;i++)  //再考虑两字符串有字符串相等的情况;        {            if(c1[i]==c2[i])                {                    if(i==0)                        ans[i]=0;                    else                       ans[i]=ans[i-1];                }            else            {                for(int j=0;j<i;j++)  //由于有相等的情况,我们需要在判断大小;                    ans[i]=min(ans[i],ans[j]+dp[j+1][i]);            }        }        printf("%d\n",ans[len1-1]);    }    return 0;}
0 0
原创粉丝点击