题意:n个字符组成长度为m的字符串str,给出了添加删除每个字符的代价,问要使得给定字符串回文做小代价是多少。
此题添加和删除字符代价是一个迷惑项,因为不论如何我们只要使得代价最小就可以,即cost=min(add, del)。
定义:dp[i][j]表示使字符串str[0..m-1]的子串str[i…j]成为回文串的最小代价。状态转移方程:
如果:s[i]==s[j],dp[i][j]=dp[i+1][j-1]
如果:s[i] !=s[j],dp[i][j]=min(dp[i+1][j]+cost[i], dp[i][j-1]+cost[j])。
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int cost[30];
int dp[2010][2010];
int main() {
int n, m;
string str;
char c;
int add, del;
cin >> n >> m;
cin >> str;
for (int i = 0; i < n; ++i) {
cin >> c >> add >> del;
cost[c - 'a'] = min(add, del);
}
memset(dp, 0, sizeof(dp));
for (int i = m - 2; i >= 0; --i) {
for (int j = i + 1; j < m; ++j) {
if (str[i] == str[j]) {
dp[i][j] = dp[i + 1][j - 1];
}
else {
dp[i][j] = min(dp[i + 1][j] + cost[str[i] - 'a'], dp[i][j - 1] + cost[str[j] - 'a']);
}
}
}
cout << dp[0][m - 1] << endl;
return 0;
}
解法二:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int cost[30];
int dp[2010][2010];
int main() {
int n, m;
cin >> n >> m;
string str;
cin >> str;
char c;
int add, del;
for (int i = 0; i < n; ++i) {
cin >> c >> add >> del;
cost[c - 'a'] = min(add, del);
}
for (int dis = 1; dis < str.size(); ++dis) { //str.size()==m
for (int i = 0, j = dis; j < str.size(); ++i, ++j) {
dp[i][j] = 100000000;
if (str[i] == str[j]) {
dp[i][j] = dp[i + 1][j - 1];
}
else {
dp[i][j] = min(dp[i + 1][j] + cost[str[i] - 'a'], dp[i][j]);//在字符串第j个字符后加字符str[i]
dp[i][j] = min(dp[i][j - 1] + cost[str[j] - 'a'], dp[i][j]);//在字符串第i个字符前加字符str[j]
}
}
}
cout << dp[0][str.size() - 1] << endl;
return 0;
}