View Code
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; int add[26],det[26],dp[2020][2020]={0}; char str[2020]; int dfs(int x,int y) { if(x>=y)return 0; if(str[x]==str[y]) { if(!dp[x+1][y-1])dp[x+1][y-1]=dfs(x+1,y-1); return dp[x+1][y-1]; } else { int t1,t2; if(!dp[x][y-1])dp[x][y-1]=dfs(x,y-1); t1=dp[x][y-1]+min(add[str[y]-'a'],det[str[y]-'a']); if(!dp[x+1][y])dp[x+1][y]=dfs(x+1,y); t2=dp[x+1][y]+min(add[str[x]-'a'],det[str[x]-'a']); return min(t1,t2); } } int main() { int n,m; while(scanf("%d%d",&n,&m)!=EOF) { char ch[3]; scanf("%s",str); for(int i=0;i<n;i++) { scanf("%s",ch); scanf("%d%d",&add[ch[0]-'a'],&det[ch[0]-'a']); } printf("%d\n",dfs(0,m-1)); break; } return 0; }