- 轻触此处传送至杭电-2476
- 请看题:
String painter
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7315 Accepted Submission(s): 3554
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.
Output
A single line contains one integer representing the answer.
Sample Input
zzzzzfzzzzz
abcdefedcba
abababababab
cdcdcdcdcdcd
Sample Output
6
7
- 就是先给你两个长度相同的字符串,问你把第一个字符串改成第二个需要的最少次数
- 变换的规则: 一次只能将一个区间的字符串涂改成同一个字母
弱弱的我曾经打算枚举了一下下,肯定会爆表于是就放弃了,因为是dp专题的题,据我推测应该是一个区间dp,虽然说有一定的板子可寻,但是小辣鸡不会写啊,只能看网上的博客,看了一通还是有有点蒙圈,只能去询问身边的巨佬,好卑微啊 Orz
这的确和普通的区间dp不一样,需要多一点奇奇怪怪的特判,有的时候能够一次性刷两个!!!
其实要将1串变为2串,主要是看2串两个相同字符之间的区间
- dp[i][j]为将[i,j]区间转换成功最少操作数
- 状态转移方程: dp[i][j]=min(dp[i][j],dp[i][k-1]+dp[k][j-1])
附上本人的辣鸡代码:详解请看代码注释 Orz
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
char a[111],b[111];
int dp[111][111],ans[111];//dp[i][j]为将[i,j]区间转换成功最少操作数
while(~scanf("%s%s",a,b)){
memset(dp,0,sizeof(dp));
int len=strlen(a);
for(int i=0;i<len;i++)
dp[i][i]=1;
for(int l=2;l<=len;l++){//枚举长度 长度肯定大于1
for(int i=0;i+l<=len;i++){//枚举起点
int j=l+i-1;//终点
dp[i][j]=dp[i][j-1]+1;
for(int k=i;k<j;k++)//断点
if(b[j]==b[k])//最小 断点与终点一样
dp[i][j]=min(dp[i][j],dp[i][k-1]+dp[k][j-1]);
}
}
for(int i=0;i<len;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]);
}
printf("%d\n",ans[len-1]);
}
return 0;
}