题目:
http://poj.org/problem?id=3280
经典的区间DP
#include <iostream> #include <cstdio> #include <cstring> #include <string> using namespace std; char s[2005], ch[2]; int cost[26]; int dp[2005][2005]; int main () { int n, m, c1, c2; scanf("%d%d%s", &n, &m, s); for(int i=0; i<n; i++) { scanf("%s%d%d", ch, &c1, &c2); cost[ch[0]-'a'] = min(c1, c2); } int len = strlen(s); for(int step=1; step<len; step++) { for(int i=0; i+step<len; i++) { int j = i+step; if(s[i]==s[j]) dp[i][j] = dp[i+1][j-1]; else dp[i][j] = min(dp[i+1][j]+cost[s[i]-'a'], dp[i][j-1]+cost[s[j]-'a']); } } printf("%d", dp[0][len-1]); return 0; }
本文通过一个POJ在线评测系统的题目实例,详细介绍了如何使用区间动态规划解决字符串处理问题。文章给出了完整的C++代码实现,并解释了核心算法思想,即通过最小化成本来匹配字符串两端字符,最终求得整个字符串的最优解。

被折叠的 条评论
为什么被折叠?



