POJ 3280 Cheapest Palindrome 简单DP


观察题目我们可以知道,实际上对于一个字母,你在串中删除或者添加本质上一样的,因为既然你添加是为了让其对称,说明有一个孤立的字母没有配对的,也就可以删掉,也能满足对称。

故两种操作看成一种,只需要保留花费少的那个即可

然后

dp[i][j]表示从位置i到j的子串转化为回文串需要的次数

若 s[i]== s[j] 则dp[i][j] = dp[i + 1][j - 1]

否则 dp[i][j] = min(dp[i+1][j] + cost[i], dp[i][j - 1] + cost[j])


#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#define MAXN 111111
#define MAXM 222222
#define INF 1000000000
using namespace std;
int n, m;
char s[2222], op[5];
int dp[2222][2222], w[33];
int main()
{
    int x, y;
    scanf("%d%d", &n, &m);
    scanf("%s", s);
    for(int i = 0; i < n; i++)
    {
        scanf("%s%d%d", op, &x, &y);
        w[op[0] - 'a'] = min(x, y);
    }
    for(int i = m - 1; i >= 0; i--)
        for(int j = i + 1; j < m; j++)
        {
            if(s[i] == s[j]) dp[i][j] = dp[i + 1][j - 1];
            else dp[i][j] = min(dp[i + 1][j] + w[s[i] - 'a'], dp[i][j - 1] + w[s[j] - 'a']);
        }
    printf("%d
", dp[0][m - 1]);
    return 0;
}


原文地址:https://www.cnblogs.com/james1207/p/3281180.html