String painter(区间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
题目大意:
给定两个等长的字符串A,B,每次操作可将一段任意区间变为一个字符,求由A变到B的最小操作次数。
#include <iostream> #include <cstring> #include <string> #include <algorithm> using namespace std; int dp[105][105],ans[105];///dp[i][j]中的i,j表示左右端点 int main() { string a,b; while(cin>>a>>b) { memset(dp,0,sizeof dp); for(int j=0;b[j];j++)///预处理一段区间内的最小次数 for(int i=j;i>=0;i--) { dp[i][j]=dp[i+1][j]+1; for(int k=i+1;k<=j;k++) if(b[i]==b[k]) dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]); } for(int i=0;a[i];i++) { ans[i]=dp[0][i]; if(a[i]!=b[i])///找更少的次数 for(int j=0;j<i;j++) ans[i]=min(ans[i],ans[j]+dp[j+1][i]); else///不刷 ans[i]=ans[i-1]; } cout<<ans[b.size()-1]<<'\n'; } return 0; }