POJ - 3280 Cheapest Palindrome(区间dp)

本文介绍了一种使用区间动态规划解决字符串转换为回文串的最小成本问题的方法。通过递归计算子问题的最优解,实现全局最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给你一个由小写字母组成的字符串s,你可以在两端添加或删除字母使其变为回文串,求最小花费。

思路:区间dp。用dp[l][r]表示l到r变为回文串的最小花费。则dp[l][r] = min(dp[l+1][r] + add[l], dp[l + 1][r] + del[l],dp[l][r - 1] + add[r], dp[l][r - 1] + del[r]).如果s[l] == s[r], 那么dp[l][r] = dp[l+1][r-1].

#include <cstdio>
#include <algorithm>
#include <iostream>
#include<vector>
#include<cmath>
#include<set>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 21e2 + 10;
const int maxt = 100200;
const int inf = 0x3f3f3f3f;
const ll INF = 0x7f7f7f7f7f;
const int mod = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-8;
int n, m;
char s[2010];
int a[27], b[27];
int dp[2010][2010];
int DP(int l, int r){
    int &ans = dp[l][r];
    if(l >= r) return ans = 0;
    if(ans != -1) return ans;
    if(s[l] == s[r]) return ans = DP(l + 1, r - 1);
    ans = inf;
    int t1 = s[l] - 'a', t2 = s[r] - 'a';
    ans = min(ans, DP(l, r - 1) + b[t2]);
    ans = min(ans, DP(l + 1, r) + b[t1]);
    ans = min(ans, DP(l, r - 1) + a[t2]);
    ans = min(DP(l + 1, r) + a[t1], ans);
    return ans;
}
int main(){
    scanf("%d%d", &n, &m);
    scanf("%s", s);
    for(int i = 0; i < n; ++i){
        char ss[2];
        int x, y;
        scanf("%s%d%d", ss, &x, &y);
        a[ss[0] - 'a'] = x;
        b[ss[0] - 'a'] = y;
    }
    memset(dp, -1, sizeof dp);
    printf("%d\n", DP(0, m - 1));
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值