# Poj 3280 cheapest palindrome DP

Source: Internet
Author: User

Given a string, adjust it to a return string. You can add or delete any character on it, but each addition or deletion of a character has a price, and the minimum price is required.
Question: The addition and deletion operations are the same, so you only need to find a small value for addition and deletion, as the cost of operating on this character.

`#include <iostream>using namespace std;int dp[2001][2001], cost[30];char s[2005];int min ( int a, int b ){return a < b ? a : b;}int main(){char ch;int n, m, add, del, i, j;//freopen("a.txt","r",stdin);scanf("%d %d",&n,&m);scanf("%s",s+1);for ( i = 1; i <= n; i++ ){getchar();scanf("%c%d%d",&ch,&add,&del);cost[ch-'a'] = min ( add, del );}for ( i = m - 1; i >= 1; i-- ){for ( j = i + 1; j <= m; j++ ){if ( s[i] == s[j] )dp[i][j] = dp[i+1][j-1];elsedp[i][j] =  min ( dp[i+1][j] + cost[s[i]-'a'], dp[i][j-1] + cost[s[j]-'a'] );}}printf("%d\n", dp[1][m] );return 0;}`

Method 2:

`#include <iostream>using namespace std;int dp[2001][2001], cost[30];char s1[2005], s2[2005];int min ( int a, int b ){return a < b ? a : b;}int main(){char ch;int n, m, add, del, i, j;scanf("%d %d",&n,&m);scanf("%s",s1+1);for ( i = 1; i <= n; i++ ){getchar();scanf("%c%d%d",&ch,&add,&del);cost[ch-'a'] = min ( add, del );}i = 1; j = m;while ( i <= m && j >= 1 ){s2[i] = s1[j];i++; j--;}dp[0][0] = 0;for ( i = 1; i <= m; i++ ){dp[i][0] = dp[i-1][0] + cost[s1[i]-'a'];dp[0][i] = dp[0][i-1] + cost[s2[i]-'a'];}for ( i = 1; i <= m; i++ ){for ( j = 1; j <= m; j++ ){if ( s1[i] == s2[j] )dp[i][j] = dp[i-1][j-1];elsedp[i][j] =  min ( dp[i-1][j] + cost[s1[i]-'a'], dp[i][j-1] + cost[s2[j]-'a'] );}}printf("%d\n", dp[m][m] / 2 );return 0;}`

Related Keywords:

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.