String painter
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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
比较好的区间dp,可以先求空串到目标串的最少操作数
然后再对原串进行dp
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 using namespace std; 9 const int MAXN=110;10 #define For(i,n) for(int i=1;i<=n;i++)11 #define Rep(i,l,r) for(int i=l;i<=r;i++)12 #define Down(i,r,l) for(int i=r;i>=l;i--)13 int dp[MAXN][MAXN];14 char str1[MAXN],str2[MAXN];15 int ans[MAXN];16 int main(){17 while(~scanf("%s%s",str1+1,str2+1)){18 int n=strlen(str1+1);19 memset(dp,0,sizeof(dp));20 For(i,n)21 Rep(j,i,n) dp[i][j]=j-i+1;22 Down(i,n-1,1)23 Rep(j,i+1,n){24 dp[i][j]=dp[i+1][j]+1;25 Rep(k,i+1,j)26 if(str2[i]==str2[k])27 dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]);28 }29 For(i,n){30 ans[i]=dp[1][i];31 if(str1[i]==str2[i]) ans[i]=ans[i-1];32 For(j,i) ans[i]=min(ans[i],ans[j]+dp[j+1][i]);33 }34 printf("%d\n",ans[n]);35 }36 return 0;37 }