hdu2476 String painter(区间dp)

题目链接:http://acm.split.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

 

思路:区间dp,Orz,这应该算是我第一道接触的区间dp的题目,刚刚看到题目的时候一点思路都没有。没办法,只能看着别人的代码硬扣!

刚接触新的知识的时候,肯定是一个挺痛苦的过程,但是请相信,只要坚持下去就会有收获的!骨头再硬我都会啃下来的。加油 区间dp!!

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ll long long
const int maxn=1e5+5;
const int INF=0x3f3f3f3f;

char str1[105],str2[105];
int dp[105][105];
int ans[105];

int main()
{
    //freopen("in.txt","r",stdin);
    while(cin>>str1+1>>str2+1)
    {
        int n=strlen(str1+1);
        for(int i=1;i<=n;i++) dp[i][i]=1;
        for(int d=1;d<n;d++)
        for(int i=1;i+d<=n;i++){
            int j=i+d;
            dp[i][j]=dp[i+1][j]+1;
            for(int 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]);
        }
        for(int i=1; i<=n; i++)ans[i]=dp[1][i];
        for(int i=1; i<=n; i++)
        if(str1[i]==str2[i]) ans[i]=ans[i-1];
        else  for(int j=1; j<i; j++) ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
        printf("%d\n",ans[n]);
    }
    return 0;
}

 

posted @ 2016-11-12 21:05  a_clown_cz  阅读(230)  评论(0)    收藏  举报