思路:
定义dp[i][j]
为将i
到j
位置的字符串转换为回文串,我们从小到大放大这个区间,定义w[c-'a']
为字母c
的花费,可得
代码:
#include<iostream>
#include<cctype>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int N=26;
const int MAX_M=2005;
int n,m,w[N],dp[MAX_M][MAX_M]; //dp[i][j]:the min cost to make the substring which from i to j legal
string s;
void solve(){
for(int i=m-2;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']);
}
}
cout<<dp[0][m-1];
}
int main(){
cin>>n>>m>>s;
for(int i=0;i<n;i++){
char c;
int w1,w2;
do{c=getchar();}while(!isalpha(c));
cin>>w1>>w2;
w[c-'a']=min(w1,w2);
}
solve();
return 0;
}