天天看點

LA 4394 String painter

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;
	}	
}