hdu2476(区间dp)

来源:互联网 发布:oracle查询不重复数据 编辑:程序博客网 时间:2024/06/04 18:27

String painter

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


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
zzzzzfzzzzzabcdefedcbaababababababcdcdcdcdcdcd
 

Sample Output
67
 

先假设a串和b串没有一个位置对应求出dp[i][j],意为从i到j转换的最小步骤,然后考虑a、b串有对应的位置

#include<iostream>#include<stdio.h>#include<string.h>using namespace std;char a[105],b[105];int dp[105][105];int ans[105];int len;int main(){while(~scanf("%s%s",a,b)){memset(dp,0,sizeof(dp));memset(ans,0,sizeof(ans));len=strlen(a);for(int j=0;j<len;j++){for(int i=j;i>=0;i--){dp[i][j]=dp[i+1][j]+1;for(int k=i+1;k<=j;k++){if(b[i]==b[k]){dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);//i与k相同,寻找i刷到k的最优方}}}}for(int i = 0; i<len; i++)              ans[i] = dp[0][i];//根据ans的定义先初始化 ,假设两个串没有一个位置对应上 //for(int i = 0; i<len; i++)cout<<"hhhhhh "<<ans[i]<<endl;         for(int i=0;i<len;i++)        {        if(a[i]==b[i])        {        ans[i]=ans[i-1];    //这个位置对应上了可以少一步操作 }else{for(int j = 0; j<i; j++)                  ans[i] = min(ans[i],ans[j]+dp[j+1][i]);//寻找j来分割区间得到最优解  }}//for(int i = 0; i<len; i++)cout<<"j "<<ans[i]<<endl;printf("%d\n",ans[len-1]);}}