hdu2476 String painter(区间dp)

题目链接:http://acm.split.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

思路:区间dp,Orz,这应该算是我第一道接触的区间dp的题目,刚刚看到题目的时候一点思路都没有。没办法,只能看着别人的代码硬扣!

刚接触新的知识的时候,肯定是一个挺痛苦的过程,但是请相信,只要坚持下去就会有收获的!骨头再硬我都会啃下来的。加油 区间dp!!

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ll long long
const int maxn=1e5+;
const int INF=0x3f3f3f3f; char str1[],str2[];
int dp[][];
int ans[]; int main()
{
//freopen("in.txt","r",stdin);
while(cin>>str1+>>str2+)
{
int n=strlen(str1+);
for(int i=;i<=n;i++) dp[i][i]=;
for(int d=;d<n;d++)
for(int i=;i+d<=n;i++){
int j=i+d;
dp[i][j]=dp[i+][j]+;
for(int k=i+;k<=j;k++)
if(str2[i]==str2[k])
dp[i][j]=min(dp[i][j],dp[i+][k]+dp[k+][j]);
}
for(int i=; i<=n; i++)ans[i]=dp[][i];
for(int i=; i<=n; i++)
if(str1[i]==str2[i]) ans[i]=ans[i-];
else for(int j=; j<i; j++) ans[i]=min(ans[i],ans[j]+dp[j+][i]);
printf("%d\n",ans[n]);
}
return ;
}
上一篇:HDU2476 String painter —— 区间DP


下一篇:Python操作redis学习系列之(集合)set,redis set详解 (六)