题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=1023
分析:
这道题是一个简单区间的dp, 状态定义为dp【i】【j】: i 到 j 这个区间形成回文的最小花费,
分两种情况讨论:
s【i】 == s【j】: dp【i】【j】 = dp【i+1】【j-1】;
s【i】 != s【j】: dp【i】【j】 = min(dp【i】【j-1】+cost【s【j】-'a'】, dp【i+1】【j】+cost【s【i】-'a'】);
cost【tt-'a'】为删除或添加字符tt的最小花费。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 2*1e3 + 10;
int dp[maxn][maxn];
int cost[maxn];
int main()
{
int n, m, a, b;
char s[maxn], ch[5];
while(~scanf("%d%d", &m, &n))
{
scanf("%s", s);
while(m--)
{
scanf("%s%d%d", ch, &a, &b);
cost[ch[0]-'a'] = min(a, b);
}
memset(dp, 0, sizeof(dp));
for(int j = 1; j < n; j++)
for(int i = j-1; i >= 0; i--)
{
if(s[i] != s[j])
dp[i][j] = min(dp[i][j-1]+cost[s[j]-'a'], dp[i+1][j]+cost[s[i]-'a']);
else
dp[i][j] = dp[i+1][j-1];
}
int ans = dp[0][n-1];
printf("%d\n", ans);
}
return 0;
}