HDU 2476 String painter(两次 区间dp)

ゝ一世哀愁。 2024-02-17 19:36 120阅读 0赞

String painter

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

  1. zzzzzfzzzzz
  2. abcdefedcba
  3. abababababab
  4. cdcdcdcdcdcd

Sample Output

  1. 6
  2. 7

题意;从第一个字符串变成第二个字符串最少的步骤,如ddddd abcba 需要三步:1、aaaaa 2、abbba 3、abcba

思路:首先预处理将一个空串变成第二个字符串需要的最少步骤,状态方程dp(i,j)=min(dp(i,k)+dp(k+1,j)) 表示从i到j的最少步骤,

然后就是找第一个字符串变成第二个字符串的最少步骤。

AC代码:

  1. #include<cstdio>
  2. #include<cstring>
  3. #include<algorithm>
  4. using namespace std;
  5. const int maxn=100+5;
  6. int dp[maxn][maxn];
  7. char a[maxn],b[maxn];
  8. int ans[maxn];
  9. int main(){
  10. while(scanf("%s%s",a+1,b+1)==2){
  11. memset(dp,0,sizeof(dp));
  12. int l=strlen(a+1);
  13. for(int i=1;i<=l;i++)dp[i][i]=1;
  14. for(int len=2;len<=l;len++) //长度
  15. for(int i=1;i<=l-len+1;i++){ //起点
  16. int j=i+len-1; //终点
  17. if(b[i]==b[j])
  18. dp[i][j]=dp[i][j-1];
  19. else dp[i][j]=dp[i][j-1]+1;
  20. for(int k=i;k<j;k++){ //找分割点
  21. dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
  22. }
  23. }
  24. for(int i=1;i<=l;i++)
  25. ans[i]=dp[1][i];
  26. for(int i=1;i<=l;i++){
  27. if(a[i]==b[i])
  28. ans[i]=ans[i-1]; //当时写成=dp[1][i-1],这个错误找了n久!!!(因为如果有对应位置相同,ans[i-1]!=dp[1][i-1])
  29. else {
  30. for(int k=1;k<i;k++)
  31. ans[i]=min(ans[i],ans[k]+dp[k+1][i]);
  32. }
  33. }
  34. printf("%d\n",ans[l]);
  35. }
  36. return 0;
  37. }

发表评论

表情:
评论列表 (有 0 条评论,120人围观)

还没有评论,来说两句吧...

相关阅读

    相关 区间dp

    概念 区间dp就是在区间上进行动态规划,求解一段区间上的最优解。主要是通过合并小区间的 最优解进而得出整个大区间上最优解的dp算法。 借鉴大佬总结:[猛戳][Link

    相关 计数dp hdu 4055 Number String

        嗯,什么是计数dp我也不知道,这是第一次遇见类似的题目。 题意:给一个只含‘I','D','?'三种字符的字符串,I表示当前数字大于前面的数字,D表示当前的数字小于前

    相关 区间dp

    让我求解在一个区间上的最优解,那么我把这个区间分割成一个个小区间,求解每个小区间的最优解,再合并小区间得到大区间即可。所以在代码实现上,我可以枚举区间长度len为每次分割成的小

    相关 [UVA1437] String painter

    [题目链接][Link 1] 题意   有两个由小写英文字母组成的等长字符串A和B。你可以一次性将一个字符串的一个子串中的字符全部刷成任何你想要同一字符。求把字符串A刷成B