hdu2476 String painter
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
题意: 给出两个字符串a,b,将a串变为b串,每次可以将连续的一个子串改成任意的一个字母,问最少需要操作多少次。 先考虑空串变为b串的情况:设dp[i][j]表示从i到j至少要变多少次,则有dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j])(i<=k<j) 然后再考虑a串,因为a串中有和b串相同的字符,所以可能使操作数更少,设f[i]表示使a[1]~a[i]==b[1]~b[i]的最小步数,则有f[i]=min(f[j]+dp[j+1][i],dp[1][i],f[i-1](当a[i]==b[i]时) ),a串中的[j+1,i]可以看做一个空串。
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
#define ll long long
#define inf 999999999
char s1[106],s2[106];
int dp[106][106],f[106];
int main()
{
int n,m,i,j,len1,k,len,flag;
while(scanf("%s",s1+1)!=EOF)
{
scanf("%s",s2+1);
len1=strlen(s1+1);
for(i=1;i<len1;i++){
dp[i][i]=1;
if(s2[i]==s2[i+1]){
dp[i][i+1]=1;
}
else dp[i][i+1]=2;
}
dp[len1][len1]=1;
for(len=3;len<=len1;len++){
for(i=1;i+len-1<=len1;i++){
j=i+len-1;
dp[i][j]=len;
if(s2[i]==s2[j]){
dp[i][j]=dp[i][j-1];continue;
}
for(k=i;k<j;k++){
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
}
}
}
if(s1[1]==s2[1]) f[1]=0;
else f[1]=1;
for(i=2;i<=len1;i++){
if(s1[i]==s2[i]){
f[i]=f[i-1];continue;
}
f[i]=dp[1][i];
for(k=1;k<i;k++){
if(s1[k]==s2[k]){
f[i]=min(f[i],f[k]+dp[k+1][i]);
}
}
}
printf("%d\n",f[len1]);
}
return 0;
}