【区间dp】hdu 2476 String painter

String painter

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


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
 
 
先考虑由空白转到B串的方案数(利用区间dp)
然后再加一个普通dp,计算由A到B串的方案
 
代码
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
char a[110],b[110];
int dp[110][110];
int ans[110];
int main(){
    while(scanf("%s%s",a,b)!=EOF){
        int len=strlen(a);
        int cnt=1;
        for(int i=0;i<len;i++){
            dp[i][i]=1;
        }        
        for(int i=1;i<len;i++){
            for(int j=0;i+j<len;j++){
                dp[j][i+j]=1e9;
                for(int k=j;k<=i+j;k++){
                    if(k!=j&&b[j]==b[k])
                    dp[j][i+j]=min(dp[j][i+j],dp[j+1][k]+dp[k+1][i+j]);
                    else
                    dp[j][i+j]=min(dp[j+1][i+j]+1,dp[j][i+j]);
                }
            }            
        }
        for(int i=0;i<len ;i++){
            if(a[i]==b[i]){
                if(i==0){
                    ans[i]=0;
                }
                else
                ans[i]=ans[i-1];
            }
            else{
                ans[i]=dp[0][i];
                for(int j=0;j<i;j++)
                ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
            }
        }
        printf("%d\n",ans[len-1]);
        
    }
}

 

posted @ 2020-11-30 17:34  andyc_03  阅读(68)  评论(0编辑  收藏  举报