关闭

LA 4394 String painter

标签: ACM好题
237人阅读 评论(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;
	}	
} 


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:63126次
    • 积分:3951
    • 等级:
    • 排名:第7933名
    • 原创:345篇
    • 转载:2篇
    • 译文:0篇
    • 评论:34条
    最新评论