Topic link:
POJ-3280
gist:
Given a string, give the cost of deleting and adding each letter (cost) and asking for the minimum cost to make it a palindrome
Analysis:
Consider the interval DP equation, dp(i,j) represents the minimum cost from i to j, then i to j has been considered the palindrome.
For the dp(i,j) direction, there are dp(i+1,j) and dp(i,j-1) two, take the smaller value from the two ways of adding and deleting respectively
dp equation:
if s[i] == s[j]
dp[i][j]=dp[i+1][j-1];
else
dp[i][j]=
min{
dp[i+1][j]+min(a[s[i]],d[s[i]]);
dp[i][j-1]+min(a[s[j]],d[s[j]]);
}
Implementation:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
#define mem(s,t) memset(s,t,sizeof(s))
#define D(v) cout<<#v<<" "<<v<<endl
#define inf 0x3f3f3f3f
#define pb push_back
#define mk make_pair
#define fi first
#define se second
#pragma warning(disable:4996)
#pragma comment(linker, "/STACK:336777216")
//#define LOCAL
const int mod = 1e9 + 7;
const int MAXN = 2e3 + 10;
int n,m;
string s,ss;
map<char,int> a,d;
int dp[MAXN][MAXN];
int main() {
mem(dp,0);
cin>>m>>n;
cin>>s;
for(int i=0;i<m;i++){
cin>>ss;
cin>>a[ss[0]]>>d[ss[0]];
}
for(int len=1;len<=n;len++){
for(int i=0;i+len<n;i++){
int j=i+len;
if(s[i]==s[j]){
dp[i][j]=dp[i+1][j-1];
}
else {
int ans1=dp[i+1][j]+min(a[s[i]],d[s[i]]);
int ans2=dp[i][j-1]+min(a[s[j]],d[s[j]]);
dp[i][j]=min(ans1,ans2);
}
}
}
cout<<dp[0][n-1]<<endl;
return 0;
}