以案例给出的abcb为例
假定字符串abcb的子串ab,形成回文字符串有四种构造方法
1.删除开头的a ab=>b
2.删除结尾的b ab=>a
3.在结尾增加a ab=>aba
4.在开头增加b ab=>bab
经过以上四种构造方法,便已然讲ab构成回文串的费用记录于数组中由以上类推,此dp的重叠子问题是:
其实对于此题而言,我们只是操作开头和末尾两个字符
由此推来:子串ax...xb //x..xb是回文串 ax..x是回文串
dp[i][j]=min{dp[i+1][j]+min{去掉a的代价,加上a的代价},dp[i][j-1]+min{去掉b的代价, 加上b的代价}} //ij是指字符串中子串从i位到j位
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <queue>
#include <map>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;
#define MP make_pair
#define PB push_back
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
typedef pair<int, int> PII;
typedef long long LL;
typedef __int64 LL1;
const double pi = 3.141592653;
const int MOD = 1e9 + 7;
const int maxn = 2e3 + 25;
const double eps = 1e-7;
char s[maxn];
int le[26][2];
int dp[maxn][maxn];
int main()
{
int n, m, i, a, b, j;
char c[2];
while( ~scanf("%d%d", &n, &m) ){
getchar();
scanf("%s", s);
getchar();
memset(le, 0, sizeof(le));
while(n--){
scanf("%s%d%d", c, &a, &b);
le[c[0]-'a'][0] = a;
le[c[0]-'a'][1] = b;
}
for( i=m-1; i>=0; i-- ){
for( j=i; j<m; j++ ){
if( i==j ){
dp[i][j] = 0;
continue;
}
dp[i][j] = min(dp[i+1][j]+ min(le[s[i]-'a'][0], le[s[i]-'a'][1]),
dp[i][j-1]+ min(le[s[j]-'a'][0], le[s[j]-'a'][1]));
if( s[i]==s[j] ){
dp[i][j] = min(dp[i][j], dp[i+1][j-1]);
continue;
}
}
}
printf("%d\n", dp[0][m-1]);
}
return 0;
}