Test instructions: Give you a M-bit string, where the character is one of the given n lowercase letters, and then the cost of adding or removing the letter in the string
Not the same. It is the minimum cost of the string to be a palindrome after adding a delete operation.
Idea: Consider D[i][j] as the minimum cost of a palindrome string I to J.
such as xx.....yy, if x = = Y, obviously d[i][j] = d[i+1][j-1];
if x! = Y, then there are 4 scenarios: Delete x, add an x after Y, delete y, and add y before x. So the transfer equation can be written
D[i][j] = min (d[i+1][j]+del[s[i]-' a '), d[i+1][j]+add[s[i]-' a '], d[i][j-1] + del[s[j]-' A '], d[i][j-1] + add[s[j]-' a ']);
From the above equation can be analyzed, for the deletion of the added character S[i], we only use to get the least cost of operation on it, and thus the equation is much shorter
such as d[i][j] = min (d[i+1][j]+cost[s[i]-' a '), D[i][j-1] + cost[s[j]-' a ']);
AC Code:
#include <cstdio> #include <algorithm> #include <cstring>using namespace std;const int M = 2005;int N,m, Ch[2],cost[27],d[m][m];char s[m];void Solve () {memset (d, 0, sizeof (d)); for (int dis = 1; dis < M; dis++) {for (int i = 0, J = I+dis; J < M; i++,j++) {if (s[i] = = S[j]) d[i][j] = d[i+1][j-1];else{d[i][j] = min (d[i+1][j] + cost[s[i]-' A '], d[i][j-1] + cost[s[j]-' a ']) ;}}} printf ("%d\n", D[0][m-1]);} int main () {while (~SCANF ("%d%d", &n, &m)) {memset (cost, 0, sizeof); scanf ("%s", s); for (int i = 0; i < n; i+ +) {int t1,t2;scanf ("%s%d%d", ch,&t1, &t2); cost[ch[0]-' a '] = min (t1,t2);} Solve ();} return 0;}
POJ 3280 Cheapest palindrome DP