我弱啊

导航

HDOJ 题目2474 String painter(区间DP)

String painter

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2520    Accepted Submission(s): 1134


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
 

 

Recommend
lcy   |   We have carefully selected several similar problems for you:  2480 2481 2478 2482 2474 
 题目大意:给你两串,每次操作能把a串的任意一段都变成任意同一个小写字母,问最少操作多少次可以变成b串
15MS 1452K
#include<stdio.h>
#include<string.h>
#define min(a,b) (a>b?b:a)
int dp[110][110],ans[110];
char str1[110],str2[110];
int main()
{
	while(scanf("%s%s",str1+1,str2+1)!=EOF)
	{
		int i,j,k;
		int len=strlen(str1+1);
		memset(dp,0,sizeof(dp));
		memset(ans,0,sizeof(ans));
		for(i=1;i<=len;i++)
			dp[i][i]=1;
		for(i=len-1;i>=1;i--)//a串和b串一个也不相等时
		{
			for(j=i+1;j<=len;j++)
			{
				dp[i][j]=dp[i+1][j]+1;
				for(k=i+1;k<=j;k++)
				{
					if(str2[i]==str2[k])
					{
						dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]);
					}
				}
			}
		}
		for(i=1;i<=len;i++)
		{
			ans[i]=dp[1][i];
			if(str1[i]==str2[i])
			{
				ans[i]=ans[i-1];
			}
			else
			{
				for(j=1;j<i;j++)
				{
					ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
				}
			}
		}
		printf("%d\n",ans[len]);
	}
}

  

posted on 2015-10-05 17:37  我弱啊  阅读(135)  评论(0编辑  收藏  举报