poj_3280 cheapest palindrome (DP)

Source: Internet
Author: User

please point me in the question.

The following:

The title means there is a string with a length of M, a total of n letters, you can add or remove letters based on the string, so that the string is a palindrome string.

The topic looks more complex, the string can be increased or subtracted, the position of the increase or decrease is uncertain. After referring to other people's blog found that in fact the effect is the same, only need to pick the best one method is good. Minus one letter, the effect is equivalent to adding that letter in a corresponding position.

The length of 1 is itself a palindrome string, as the string length increases, we can choose to add the corresponding letters on both sides of the string, so according to the interval DP, traversing interval length.

DP definition: dp[i][j], the length of the string from I to J is converted to the minimum cost of palindrome.

Recursive relationship:

0.S[I]=S[J]

DP[I][J] = dp[i+1][j-1];

1.S[I]!=S[J]

Dp[i][j] = min (left plus s[i], right plus s[j])


Reference Blog


Code implementation:

#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> using namespace std;
const int max_n = 30;
const int max_m = 2010;

const int INF = 0X7FFFFFF;
int n,m;
int Add[max_n];
Char Str[max_m];
int dp[max_m][max_m];
    int main () {scanf ("%d%d", &n,&m);
    scanf ("%s", str);
        for (int i = 0; i < N; i++) {int A, B;
        char tmp;
        GetChar ();
        scanf ("%c%d%d", &tmp,&a,&b);
    add[tmp-' a '] = min (a, b);
    } memset (Dp,0,sizeof (DP));
            for (int k = 1, k <= M-1; k++) {for (int i=0,j=k; j < M; i++,j++) {dp[i][j] = INF;
            if (str[i] = = Str[j]) {dp[i][j] = dp[i+1][j-1];
                } else{int left = str[i]-' a ';
                int right = str[j]-' a ';
            Dp[i][j] = min (dp[i][j],min (dp[i+1][j]+add[left],dp[i][j-1]+add[right]));
    }}} printf ("%d\n", dp[0][m-1]); Return 0;
 }


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.