POJ 3280 Cheapest palindrome DP

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.