dp
View Code
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; #define maxn 205 #define maxm 2005 #define inf 0x3f3f3f3f int n, m; char st[maxm]; int cost[maxn]; int f[maxm][maxm]; void input() { scanf("%d%d", &n, &m); scanf("%s", st + 1); for (int i = 0; i < n; i++) { char ch[5]; int a, b; scanf("%s%d%d", ch, &a, &b); cost[(int)ch[0]] = min(a, b); } } int work() { // f[i][j] = min(f[i - 1][j] + cost[i], f[i][j + 1] + cost[j]) // f[i][j] = f[i - 1][j + 1] f[0][m + 1] = 0; for (int i = m; i > 0; i--) f[0][i] = cost[(int)st[i]] + f[0][i + 1]; for (int i = 1; i <= m; i++) f[i][m + 1] = f[i - 1][m + 1] + cost[(int)st[i]]; for (int i = 1; i < m; i++) { for (int j = m; j > i; j--) { f[i][j] = min(f[i - 1][j] + cost[(int)st[i]], f[i][j + 1] + cost[(int)st[j]]); if (st[i] == st[j]) f[i][j] = min(f[i][j], f[i - 1][j + 1]); } } int ret = inf; for (int i = 1; i <= m; i++) ret = min(ret, f[i - 1][i + 1]); for (int i = 1; i < m; i++) ret = min(ret, f[i][i + 1]); return ret; } int main() { //freopen("t.txt", "r", stdin); input(); printf("%d\n", work()); return 0; }