String painter
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5530 Accepted Submission(s): 2629
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.
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
题解:先求空串转化为str2的值;考虑区间[i,j],i<=k<=j,如果s[i]=s[k],那么dp[i][j]=dp[i+1][k-1]+dp[k][j];即求区间[i,j]转化为区间[i+1,j]。如ac aba->c aba, 而 aba->ba。
由str1求str2的次数,记ans[i]为区间[0,i]转化的最优解,那么j=i+1,区间ans[j]=min(ans[j],ans[k]+dp[k+1][j]),0<=k<j;
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,a,n) for(int i=(a);i<(n);++i)
#define per(i,a,n) for(int i=(n-1);i>=(a);--i)
#define INF 1e9
const int mod=1e9+7;
#define N 110
char a[N],b[N];
int dp[N][N];
int main(){
ios::sync_with_stdio(0);
int n;
while(scanf("%s",a)!=-1){
scanf("%s",b);
n=strlen(a);
memset(dp,0,sizeof(dp));
for(int i=0;i<n;++i) dp[i][i]=1;
for(int l=1;l<n;++l){
for(int i=0;i+l<n;++i){
int j=i+l;
dp[i][j]=dp[i+1][j]+1;
for(int k=i;k<=j;++k){
if(b[i]==b[k]){
dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]); //[i,j]等价于 [i+1,j]
} //aabaa ->abaa ->baa=2 ,aa->a=1;
}
//cout<<"l="<<l<<' '<<i<<' '<<j<<' '<<dp[i][j]<<endl;
}
}
int ans[N];
for(int i=0;i<n;++i){
ans[i]=dp[0][i]; //全用空白串替换
if(a[i]==b[i]){
if(i==0) ans[i]=0;
else ans[i]=ans[i-1];
}
for(int k=0;k<i;++k){
ans[i]=min(ans[i],ans[k]+dp[k+1][i]);
}
}
cout<<ans[n-1]<<endl;
}
return 0;
}