POJ 3280 Cheapest Palindrome DP question
When we see the Palindrome question, we should first think about the central issue, and then start from the center and think about how to solve it.
DP problems are generally converted from smaller problems to larger problems, and then computed from bottom up to bottom up.
It is easy to get the state transition equation. The state transition equation in this question is:
If (cowID [I] = cow {j]) tbl [id] [I] = tbl [id] [I + 1]; // you do not need to change it when the values are equal.
Else tbl [id] [I] = min (tbl [! Id] [I + 1] + cost [cowID [I]-'a'], tbl [! Id] [I] + cost [cowID [j]-'a']); // it is more cost-effective to change the character on the other side if it is not equal.
Note:
The Delete and insert operations of 1 cost are the same for DP, so you only need to report the smallest cost.
2 The cost value is saved by the letter as the subscript, not given in order, or the value of some letters may not be given. At this time, it should be zero by default.
Finally, we need to save memory. These questions can generally be viewed only by the one-dimensional dp table array. At this time, we need to convert two-dimensional data into one-dimensional data storage results, saving a lot of memory in actual testing.
Here we use the so-called rolling array and use two arrays in turn to record data.
This mainly converts the diagonal lattice of the orders table into an array for saving, corresponding to the subscript.
#include
#include
const int MAX_M = 2001;const int MAX_N = 26;char cowID[MAX_M];int cost[MAX_N];//minimum of the cost of adding and deleting that character.int tbl[2][MAX_M];int N, M;inline int min(int a, int b) { return a < b ? a : b; }int getMinCost(){memset(tbl[0], 0, sizeof(int)*M);memset(tbl[1], 0, sizeof(int)*M);bool id = false;for (int d = 2; d <= M; d++){id = !id;for (int i = 0, j = d-1; j < M; i++, j++){if (cowID[i] == cowID[j]) tbl[id][i] = tbl[id][i+1];else{int c1 = tbl[!id][i+1] + cost[cowID[i]-'a'];int c2 = tbl[!id][i] + cost[cowID[j]-'a'];tbl[id][i] = min(c1, c2);}}}return tbl[id][0];}int main(){char a;int c1, c2;while (scanf("%d %d", &N, &M) != EOF){memset(cost, 0, sizeof(int)*N);getchar(); gets(cowID);for (int i = 0; i < N; i++){a = getchar();scanf("%d %d", &c1, &c2);cost[a-'a'] = min(c1, c2);//only need to save the minimumgetchar();}printf("%d\n", getMinCost());}return 0;}