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
題意:
把字符串a變成字符串b,每次可以使一段區間變成同一個字母。問最少變換次數。
題解:
如果直接對兩個字符串進行比較跑dp,狀態會很複雜也很難轉移(我搞了很久都還沒搞出來),但如果先進行一個預處理,用dp[i][j]表示將一個空的字符串變成字符串b,對[i,j]這個區間最少需要進行的操作次數,然後再算將a變成b就很簡單了。(a到b的最壞情況就是將a看成一個空字符)。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100 + 10;
int n;
int dp[N][N],f[N];
char s1[N],s2[N];
int main(){
while(~scanf("%s%s",s1,s2+1)){
n=strlen(s1);
for(int i=n;i>=1;--i) s1[i]=s1[i-1];
memset(dp,63,sizeof(dp));
memset(f,63,sizeof(f));
for(int i=1;i<=n;++i) dp[i][i]=1,dp[i][i-1]=0;
for(int len=2;len<=n;++len){
for(int i=1;i+len-1<=n;++i){
int j=i+len-1;
dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1;
if(s2[i]==s2[j]) dp[i][j]=min(dp[i][j],dp[i+1][j-1]+1);
for(int k=i;k<=j;++k){
if(s2[i]==s2[k])
dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]);
}
}
}
f[0]=0;
for(int i=1;i<=n;++i){
if(s1[i]==s2[i]) f[i]=f[i-1];
else f[i]=f[i-1]+1;
for(int j=0;j<=i;++j) f[i]=min(f[i],f[j]+dp[j+1][i]);
}
printf("%d\n",f[n]);
}
return 0;
}
還是把直接搞區間dp的代碼發上來。。。
下面是我WA掉的代碼:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100 + 10;
int dp[N][N];
char s1[N],s2[N];
int main(){
while(~scanf("%s%s",s1,s2)){
int n=strlen(s1);
for(int i=n;i>=1;--i) s1[i]=s1[i-1],s2[i]=s2[i-1];
memset(dp,63,sizeof(dp));
for(int i=1;i<=n;++i){
if(s1[i]==s2[i]) dp[i][i]=0;
else dp[i][i]=1;
dp[i][i-1]=0;
}
for(int len=2;len<=n;++len){
for(int i=1;i+len-1<=n;++i){
int j=i+len-1;
dp[i][j]=min(dp[i][j],dp[i+1][j-1]+(s1[i]!=s2[i])+(s1[j]!=s2[j]));
dp[i][j]=min(dp[i][j],dp[i+1][j]+(s1[i]!=s2[i]));
dp[i][j]=min(dp[i][j],dp[i][j-1]+(s1[j]!=s2[j]));
for(int k=i;k<=j;++k){
dp[i][j]=min(dp[i][j],dp[i][k-1]+dp[k+1][j]+(s1[k]!=s2[k]));
if(s2[i]==s2[k]&&s2[k]!=s1[k]) dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]);
else if(s2[i]==s2[k]&&s1[i]==s2[i]&&s2[k]==s1[k]) dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]);
else dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]+(s1[i]!=s2[i]));
}
}
}
printf("%d\n",dp[1][n]);
}
return 0;
}