HDU - 2476 ——区间dp

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数组之中,再匹配ans数组,ans存的是最终结果。

#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
int dp[105][105];
int main()
{
     char s1[105],s2[105];
     int ans[105];
     while(scanf("%s",s1+1)!=EOF)
     {
          scanf("%s",s2+1);
          int len=strlen(s1+1);
          for(int i=1;i<=len;i++)
          {
               for(int j=1;j<=len;j++)
               dp[i][j]=1e5;
               dp[i][i]=1;
          }
          for(int slen=1;slen<len;slen++)
          {
               for(int i=1;i+slen<=len;i++)
               {
                    int j=i+slen;
                    dp[i][j]=dp[i+1][j]+(s2[i]==s2[j]?0:1);
                    for(int k=i+1;k<=j;k++)
                        if(s2[i]==s2[k])
                            dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);
               }
          }
          ans[1]=s1[1]==s2[1]?0:1;
          for(int i=2;i<=len;i++)
          {
               ans[i]=dp[1][i];
               if(s1[i]==s2[i])
                   ans[i]=min(ans[i],ans[i-1]);
               for(int j=1;j<=i;j++)
                   ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
          }
      printf("%d\n",ans[len]);
     }
 return 0;
}

猜你喜欢

转载自blog.csdn.net/tianyizhicheng/article/details/82011458