Cheapest Palindrome (DP,LCS)

# include<stdio.h>
# include<string.h>
#include<algorithm>
using namespace std;
# define maxn 2005
char s[maxn];
int dp[maxn][maxn],cost[maxn];
int main()
{
    int n,m,a,b,i,j;
    char temp;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        getchar();
        scanf("%s",s+1);
        getchar();
        for(i=1;i<=n;i++)
        {
            scanf("%c %d%d",&temp,&a,&b);
            getchar();
            cost[temp-'a'] = min(a,b);
        }
        for(j=1;j<=m;j++)
            for(i=j+1;i>=1;i--)
            {
                dp[i][j] = min(dp[i+1][j]+cost[s[i]-'a'] , dp[i][j-1]+cost[s[j]-'a']) ;
                if(s[i]==s[j])
                    dp[i][j] = min(dp[i+1][j-1],dp[i][j]);
            }
        printf("%d\n",dp[1][m]);
    }
    return 0;
}
posted @ 2014-01-24 10:28  单调的幸福  阅读(166)  评论(0编辑  收藏  举报