LA 4394 String painter

185 篇文章 0 订阅
116 篇文章 0 订阅

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?


题意:给定两个长度相等,只有小写字母组成字符串A和B,每步可以把A的一个连续子串刷成同一个字母,问至少需要多少步才能把A变成B。


分析:看了题解才会做,设f[i]为前i个字符刷成B的最小次数,则当b[i] = b[i-1]时,f[i] = f[i-1],否则i这个位置至少刷一次;每次涂刷可以用一个区间表示[i,j],而且b[i] == b[j],否则无意义,设dp[i][j]表示i刷到j的最少次数,b[i] == b[i+1]时,dp[i][j] = dp[i+1][j],否则dp[i][j] = min(dp[i+1][k]+dp[k+1][j]) 其中 b[i] == b[k].


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define MAXN 2147483646
using namespace std;
int f[105],dp[105][105];
char a[105],b[105];
int main()
{
	while(~scanf("%s",a+1))
	{
		scanf("%s",b+1);
		int n = strlen(a+1);
		memset(f,0,sizeof(f));
		memset(dp,0,sizeof(dp));
		for(int i = n;i;i--)
		{
			dp[i][i] = 1;
			for(int j = i+1;j <= n;j++)
			{
				dp[i][j] = dp[i+1][j] + (b[i] == b[i+1] ? 0:1);
				for(int k = i+1;k <= j;k++) 
				 if(b[k] == b[i]) dp[i][j] = min(dp[i][j],dp[i+1][k]+dp[k+1][j]);
			}
		}
		for(int i = 1;i <= n;i++) 
		 if(b[i] == a[i]) f[i] = f[i-1];
		 else
		 {
		 	f[i] = MAXN;
		 	for(int j = i;j;j--)
		 	 if(b[j] == b[i]) f[i] = min(f[i],f[j-1]+dp[j][i]);
		 }
		cout<<f[n]<<endl;
	}	
} 


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值