动态规划_线性结构例题_Color Length(UVA1625)
2015-08-06 15:00
363 查看
【Color Length(UVA1625)】
【解析】
很难想到这是一个DP问题,看到的题意和思路都不太明晰,于是决定自己亲手做一做。建立一个模型,求出状态:str1、str2分别拿出i、j个字符时的最优解。
dp(i,j) = min{dp(i-1,j), dp(i, j-1)} + temp
其中,temp是还有多少个字符没有结束。可由预处理简化判断。
【代码】
#include<iostream> #include<cstring> #include<string> using namespace std; const int maxn = 5000; const int INF = 1<<30; int dp[maxn+10][maxn+10]; int color1[32][2], color2[32][2]; int main() { string str1, str2; int n; cin>>n; while(n--) { str1.clear(); str2.clear(); cin>>str1>>str2; memset(color1, -1, sizeof(color1)); memset(color2, -1, sizeof(color2)); int len1 = str1.length(), len2 = str2.length(); for(int i=0; i<len1; i++) if(color1[str1[i]-'A'][0]==-1) { color1[str1[i]-'A'][0] = i; color1[str1[i]-'A'][1] = i; } else color1[str1[i]-'A'][1] = i; for(int i=0; i<len2; i++) if(color2[str2[i]-'A'][0]==-1) { color2[str2[i]-'A'][0] = i; color2[str2[i]-'A'][1] = i; } else color2[str2[i]-'A'][1] = i; for(int i=0; i<=len1; i++) for(int j=0; j<=len2; j++) { int ans; ans = 0; for(int k=0; k<26; k++) if(((color1[k][0]>-1 && color1[k][0]<=i-1) || (color2[k][0]>-1 && color2[k][0]<=j-1)) && (color1[k][1]>i-1 || color2[k][1]>j-1)) ans++; dp[i][j] = min(i-1>=0?dp[i-1][j]:INF, j-1>=0?dp[i][j-1]:INF) + ans; if(!i && !j) dp[0][0] = 0; } cout<<dp[len1][len2]<<endl; } return 0; }
相关文章推荐
- C++动态规划之最长公子序列实例
- C++动态规划之背包问题解决方法
- C#使用动态规划解决0-1背包问题实例分析
- 动态规划
- C++ 动态规划
- DP(动态规划) 解游轮费用问题
- 动态规划的用法——01背包问题
- 动态规划的用法——01背包问题
- 《收集苹果》 动态规划入门
- 《DNA比对》蓝桥杯复赛试题
- 《背包问题》 动态规划
- 关于爬楼梯的动态规划算法
- 动态规划 --- hdu 1003 **
- DP问题各种模型的状态转移方程
- 0-1背包解题过程
- USACO 3.2.2:Stringsobits
- 字符串编辑距离
- HDU ACM Step 2.2.2 Joseph(约瑟夫环问题)
- ACM常用算法
- 01背包问题