hdu 2476 String painter(区间dp)

                                             String painter

                                                                                               Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
                                                                                                                      Total Submission(s): 4108    Accepted Submission(s): 1915
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
题意:两个字符串AB A->B按照规则变  规则是将A字符串中【l r】区间的字符变成一个字符  问最小的变换次数
我们先用一个空串用区间dp按照规则去求出空串变成B需要的至少变换次数(dp【0】【len-1】)
最后我们根据AB字符串选择dp
if(a[i]==b[i])dp[0][i]=dp[0][i-1];

else dp[0][i]=min(dp[0][i],dp[0][j]+dp[j+1][i])    (j<i);

 

 
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cctype>
 5 #include<cmath>
 6 #include<cstring>
 7 #include<map>
 8 #include<stack>
 9 #include<set>
10 #include<vector>
11 #include<algorithm>
12 #include<string.h>
13 typedef long long ll;
14 typedef unsigned long long LL;
15 using namespace std;
16 const int INF=0x3f3f3f3f;
17 const double eps=0.0000000001;
18 const int N=1000+10;
19 char a[N],b[N];
20 int dp[N][N];
21 int DP[N];
22 int main(){
23     while(gets(a)){
24         gets(b);
25         int len=strlen(a);
26         memset(dp,INF,sizeof(dp));
27         for(int i=0;i<len;i++)dp[i][i]=1;
28         for(int t=1;t<len;t++){
29             for(int i=0;i+t<len;i++){
30                 int j=i+t;
31                 if(b[i]==b[j])dp[i][j]=dp[i][j-1];
32                 else{
33                     for(int k=i;k<j;k++)
34                     dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
35                 }
36             }
37         }
38         for(int i=0;i<len;i++){
39             if(i==0&&a[i]==b[i])dp[0][i]=0;
40             else if(a[i]==b[i])dp[0][i]=dp[0][i-1];
41             for(int j=0;j<i;j++)
42             dp[0][i]=min(dp[0][i],dp[0][j]+dp[j+1][i]);
43         }
44         cout<<dp[0][len-1]<<endl;
45     }
46 }

 

 

posted on 2017-05-10 00:09  见字如面  阅读(285)  评论(0编辑  收藏  举报

导航