Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=2476
One: Test instructions:
Given your two string str1 and str2,str1 as the initial string, str2 is the target string. I want you to turn str1 into a str2 string,
The only thing you can do is to select a contiguous interval in the str1 to turn it all into the same letter (any lowercase letter).
Ask you str1 at least how many times this operation can become str2.
Second, the analysis:
I first calculate if a blank string becomes the minimum number of steps required for str2.
Dp[j][i] indicates that the interval [j,i] blank string becomes STR2 minimum number of steps. Recursive equation:
if (Str2[j]==str2[k])
Dp[i][j]=min (Dp[i][j],dp[j+1][k]+dp[k+1][i]).
Sun[i] indicates that the interval [0,i] str1 becomes the STR2 minimum number of steps. The sun array is initialized with DP Sun[i]=dp[0][i].
Here are two points to note:
(1) for Dp[i][j], the J-node of the interval [i,j] is bound to be dyed. This is the source of the recursive equation.
(2), for the implementation of DP to pay attention as long as it has been calculated that the recorded must be optimal, we have to do is to use the existing
Optimal value to be calculated at the moment.
Three, code:
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h>using namespace Std;char str1[150],str2[150];int Dp[150][150];//dp[i][j] blank string changes to the target string in the interval [i,j] The minimum number of steps (optimal)//note: Each interval [x, y] The last node is bound to be dyed so Dp[i][i]==1;int sun[150];//sun[i] is recorded in the interval [0,i] on the str1 into STR2 minimum steps int main () {while (scanf ("%s%s", STR1,STR2 !=eof) {int Len=strlen (STR2);//blank string dyed str2 memset (dp,0,sizeof (DP)); for (int i=0;i<len;i++) {for (int j=i;j>=0;j--) {//interval [j,i] Dp[j][i]=d p[j+1][i]+1;//j node separate staining for (int k=j+1;k<=i;k++) {//interval insert K if (str2[k]= =STR2[J])//Two can be brushed together {dp[j][i]=min (dp[j][i],dp[j+1][k]+dp[k+1][i]); Dp[j+1][k] indicates that the K-node must be individually stained}}}} for (int i= 0;i<len;i++) Sun[i]=dp[0][i]; for (int i=0;i<len;i++){if (Str1[i]==str2[i]) sun[i]=sun[i-1]; else {//use two best to calculate sun[i] optimal for (int j=0;j<i;j++) sun[i]=min (sun[i],sun[j]+ Dp[j+1][i]); }} printf ("%d\n", sun[len-1]); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 2476 interval DP