zoukankan      html  css  js  c++  java
  • 挑战练习题2.3动态规划 poj3280Cheapest Palindrome 区间dp

    题目链接:

    http://poj.org/problem?id=3280

    题意:

    字串S长M,由N个小写字母构成。欲通过增删字母将其变为回文串,增删特定字母花费不同,求最小花费。

    题解:

    dp[i][j]表示将原字串s的子字串s[i…j]变换成回文的最小花费
    因为删除和增加一个字符都是一样的效果,取最小值就好了

    代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 using namespace std;
     5 typedef long long ll;
     6 #define MS(a) memset(a,0,sizeof(a))
     7 #define MP make_pair
     8 #define PB push_back
     9 const int INF = 0x3f3f3f3f;
    10 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
    11 inline ll read(){
    12     ll x=0,f=1;char ch=getchar();
    13     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    14     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    15     return x*f;
    16 }
    17 //////////////////////////////////////////////////////////////////////////
    18 const int maxn = 2e3+10;
    19 
    20 string s;
    21 int cost[maxn],dp[maxn][maxn];
    22 
    23 int main(){
    24     int n,m;
    25     cin >> n >> m >> s;
    26     for(int i=0; i<n; i++){
    27         char ch; int c1,c2; cin >> ch >> c1 >> c2;
    28         cost[ch-'a'] = min(c1,c2);
    29     }
    30 
    31     // dp[i][j];
    32 
    33     for(int len=1; len<m; len++){
    34         for(int i=0; i+len<m; i++){
    35             int j = i+len;
    36             dp[i][j] = min(dp[i][j-1]+cost[s[j]-'a'],dp[i+1][j]+cost[s[i]-'a']);
    37             if(s[i]==s[j])
    38                 dp[i][j] = min(dp[i][j],dp[i+1][j-1]);
    39         }
    40     }
    41 
    42     cout << dp[0][m-1] << endl;
    43 
    44     return 0;
    45 }
  • 相关阅读:
    配置log4j不同方法打印到不同的日志中
    Logging日志信息(转)
    Mybatis 动态sql
    mysql字段截取(转)
    tomcat多个端口配置
    Map,list,set,集合转化
    简单测试java
    java中有关自增的问题
    DMA复习
    笔试题
  • 原文地址:https://www.cnblogs.com/yxg123123/p/6827618.html
Copyright © 2011-2022 走看看