版权声明:本文为博主原创文章,点个赞随便转 https://blog.csdn.net/qq_20200047/article/details/71123422
String painter
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4080 Accepted Submission(s): 1904
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
Source
Recommend
lcy
题意:给定两个字符串a和b,求最少需要对a进行多少次操作,才能将a变成b。每次操作时将a中任意一段变成任意一个字母所组成的段。
先是考虑将所有与目标字符串不相同的刷成目标串:
dp[i][j]表示刷i-j区间,
初始条件:dp[i][j]=dp[i+1][j]+1;
对于k=(i+1...j )如果str[k]==str[i],则dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]),,因为刷i的时候可以与k同时刷。
上面是对初始串与目标串完全不同的情况,
如果有部分的不同:
ans[i]表示将str1[0...i]刷成str2[0...i]的最小步数,
if str1[i]==str2[i] 则ans[i]=ans[i-1];
else
ans[i]=min(ans[i],ans[j]+dp[j+1][i]) j<i;
#include<iostream>#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
const int maxn = 300005;
const int mod =1e9+7;
int n,m;
int dp[500][500];
char a[500],b[500];
int ans[500];
int main()
{
int i,j,k,t;
int c,K;
while(scanf("%s%s",a,b)!=EOF)
{
//printf("%c\n",a[0]);
memset(dp,0,sizeof(dp));
memset(ans,0,sizeof(ans));
n=strlen(a);
for(i=0; i<n; i++)
for(j=i; j<n; j++)
dp[i][j]=j-i+1; //起初设一块石头一种颜色
for(i=n-2; i>-1; i--)//dp预处理出从每个点开始涂色的最优方案
for(j=i+1; j<n; j++)
{
dp[i][j]=dp[i+1][j]+1;//位置i要涂色,先把它预置好,再去求是否是最优的
for(k=i+1; k<=j; k++)
{
if(b[i]==b[k])//i,k最终颜色相同,在中间可以一次刷
{
dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);//即dp[i+1][j]+1,与dp[i+1][k]+dp[k+1][j]的较量
}
}
}
if(a[0]==b[0])
ans[0]=0;
else ans[0]=1;
for(i=1; i<n; i++)
{
ans[i]=dp[0][i];
if(a[i]==b[i])ans[i]=ans[i-1];
else
{
for(j=0; j<i; j++)
ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
}
}
//for(i=1;i<=n;i++)
printf("%d\n",ans[n-1]);
}
return 0;
}