String painter(区间dp,好题难题)

https://cn.vjudge.net/problem/HDU-2476

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不好办,我们可以先将一个空串转化成B,再比较与将A直接转化成B那个更快;

dp[i][j]代表空串变成B的[i,j]的最少操作

ans[i]表示A的[1, i]区间转换成B的[1, i]的最少操作

大佬学长的博客https://blog.csdn.net/Sirius_han/article/details/81323901

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
#include<list>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
char a[105],b[105];
int dp[105][105];
int ans[105];
int dfs(int l,int r){
	if(dp[l][r]!=-1) return dp[l][r];
	if(l==r) return dp[l][r]=1;
	if(l>r) return 0;
	int ans=dfs(l,r-1)+1;
	for(int i=l;i<r;i++){
		if(b[i]==b[r])
		ans=min(ans,dfs(l,i-1)+dfs(i,r-1));
	}
	return dp[l][r]=ans;
}
int main(){
    while(~scanf("%s%s",a+1,b+1)){
    	int len=strlen(a+1);
		memset(dp,-1,sizeof(dp));
		for(int i=1;i<=len;i++){
			ans[i]=dfs(1,i);
			if(a[i]==b[i]) ans[i]=ans[i-1];
			for(int j=1;j<i;j++){
				ans[i]=min(ans[i],ans[j]+dfs(j+1,i));
			}
		}
		printf("%d\n",ans[len]); 
	}
	return 0;
}



 

全部评论

相关推荐

真tmd的恶心,1.面试开始先说我讲简历讲得不好,要怎样讲怎样讲,先讲背景,再讲技术,然后再讲提升多少多少,一顿说教。2.接着讲项目,我先把背景讲完,开始讲重点,面试官立即打断说讲一下重点,无语。3.接着聊到了项目的对比学习的正样本采样,说我正样本采样是错的,我解释了十几分钟,还是说我错的,我在上一家实习用这个方法能work,并经过市场的检验,并且是顶会论文的复现,再怎么不对也不可能是错的。4.面试官,说都没说面试结束就退出会议,把面试者晾在会议里面,丝毫不尊重面试者难受的点:1.一开始是讲得不好是欣然接受的,毕竟是学习。2.我按照面试官的要求,先讲背景,再讲技术。当我讲完背景再讲技术的时候(甚至已经开始蹦出了几个技术名词),凭什么打断我说讲重点,是不能听出人家重点开始了?这也能理解,每个人都有犯错,我也没放心上。3.我自己做过的项目,我了解得肯定比他多,他这样贬低我做过的项目,说我的工作是错误的,作为一个技术人员,我是完全不能接受的,因此我就和他解释,但无论怎么解释都说我错。凭什么,作为面试官自己不了解相关技术,别人用这个方式work,凭什么还认为这个方法是错的,不接受面试者的解释。4.这个无可厚非,作为面试官,不打招呼就退出会议,把面试者晾着,本身就是有问题。综上所述,我现在不觉得第一第二点也是我的问题,面试官有很大的问题,就是专门恶心人的,总结面试官说教,不尊重面试者,打击面试者,不接受好的面试者,技术一般的守旧固执分子。有这种人部门有这种人怎么发展啊。最后去查了一下,岗位关闭了。也有可能是招到人了来恶心人的,但是也很cs
牛客20646354...:招黑奴啊,算法工程师一天200?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务