POJ 3280 Cheapest palindrome (interval dp)

Source: Internet
Author: User
Tags min

Test instructions: Give a string, you want to put him into a palindrome, ask the minimum cost.

Solution: Initially thought only on both sides to add the letter, and then always WA. Later took someone else's program found can be in the middle of the letter.

DP, DP[I][J] represents the minimum cost of i-j string into palindrome strings.

Transfer equation: If the characters of I and J are the same, then the minimum cost of the strings they surround is directly. DP[I][J] = dp[i-1][j-1].

If it is not the same, then take the minimum value of the change on both sides. Dp[i][j] = min (Dp[i+1][j] + change[i], dp[i][j-1] + change[j]);

The code is as follows:

#include <iostream> #include <cstdio> #include <vector> #include <queue> #include <utility > #include <stack> #include <algorithm> #include <cstring> #include <string> #include <
cmath> #include <set> #include <map> using namespace std;
const int MAXN = 2e4 + 5;
int n, m;
Char STR[MAXN], ch[5];
int ADD[MAXN];

int DP[MAXN][MAXN]; int main () {#ifndef Online_judge freopen ("In.txt", "R", stdin),//Freopen ("OUT.txt", "w", stdout), #endif scanf ("%d
	%d ", &n, &m);
	scanf ("%s", str + 1);
		for (int i = 0, a, b; i < n; i++) {scanf ("%s%d%d", ch, &a, &b);
	Add[ch[0]] = min (a, b);
			} for (int k = 2, K <= m; k++) {for (int i = 1; I <= m; i++) {Int J = i + k-1; if (str[i] = = Str[j]) {Dp[i][j] = dp[i + 1][j-1];//If i+1 is greater than j-1 does not matter, the state that is not established is 0 cost} else {Dp[i][j] = min (dp[i + 1
			][J] + add[str[i]], dp[i][j-1] + add[str[j]);
	}}} printf ("%d\n", Dp[1][m]);
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.