HDU 2476 String painter(区间dp+普通dp) 题解

18 篇文章 0 订阅
5 篇文章 0 订阅

题目来源:

http://acm.hdu.edu.cn/showproblem.php?pid=2476

题目描述:

 

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

 

 

Source

2008 Asia Regional Chengdu

 

 

Recommend

lcy

解题思路:

      题目大意就是给你两个串,一次操作可以将a串的一个区间变成相同的一个字符,问从a串到b串,最少需要多少次操作;

      解题分为两步,先考虑从空串到b串最少需要多少次,设dp[i][j]为从i到j变成b串需要多少次,已知dp[i][i]=1;我们可以初始化dp[i ][j ]=dp[i+1][j]+1,如果s2【i】=s2【k】,dp[i][]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]),因为如果i位和k位相同那么从i到j就相当于i+1到j。

      然后就是用一个数组ans[i]表示从1到i,s1到s2需要多少次,我们可以得出,ans[i]=min(dp[j][i]+ans[j],dp[1][i])当s1[i]==s2[i]时ans[i]=ans[i-1];

代码:

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int  maxn=1e5+10;
string a,b;
int dp[110][110],ans[110];
int main()
{
	while(cin>>a>>b)
	{
		memset(dp,0,sizeof(dp));
		int len=a.length();
		for(int i=0;i<len;i++)dp[i][i]=1;
		for(int l=2;l<=len;l++)
		for(int i=0;i<=len-l;i++)
		{
			int j=l+i-1;
			dp[i][j]=dp[i+1][j]+1;
			for(int k=i+1;k<=j;k++)
			if(b[i]==b[k])dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);
		}

		for(int i=0;i<len;i++)ans[i]=dp[0][i];
		for(int i=0;i<len;i++)
		{
			if(a[i]==b[i])ans[i]=ans[i-1];
			else
				for(int j=0;j<i;j++)
				ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
		}
		cout<<ans[len-1]<<endl;	
	}
	return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值