zoukankan      html  css  js  c++  java
  • poj 3280 Cheapest Palindrome

    题目大意:一个字符串,用已知的字符把它变为回文串时,代价最小是多少?其中添加一个字符或删除一个字符都有相应代价。

    Input

    Line 1: Two space-separated integers: N and M
    Line 2: This line contains exactly M characters which constitute the initial ID string
    Lines 3..N+2: Each line contains three space-separated entities: a character of the input alphabet and two integers which are respectively the cost of adding and deleting that character.

    Output

    Line 1: A single line with a single integer that is the minimum cost to change the given name tag.

    Sample Input

    3 4
    abcb
    a 1000 1100
    b 350 700
    c 200 800

    Sample Output

    900

    Hint

    If we insert an "a" on the end to get "abcba", the cost would be 1000. If we delete the "a" on the beginning to get "bcb", the cost would be 1100. If we insert "bcb" at the begining of the string, the cost would be 350 + 200 + 350 = 900, which is the minimum.
     
    动态规划。
    dp[i][j]表示由位置i到位置 j的子串变成回文串所需要的代价
    如果str[i] == str[j] ,那么dp[i][j] = dp[i+1][j-1]
    如果str[i] != str[j] , 那么 dp[i][j] = min(dp[i][j-1] + cost[str[j] - 'a'], dp[i+1][j] + cost[str[i] - 'a']);
    即把i到j-1变为回文串的代价再加上加一个或减一个边缘字母的代价  和
      把i+1到j变为回文串的代价再加上加一个或减一个边缘字母的代价 的最小值
     
    代码如下
     1 #include <cstdio>
     2 #include <cstdlib>
     3 #include <cstring>
     4 #include <iostream>
     5 using namespace std;
     6 
     7 char str[2002];
     8 int dp[2002][2002];
     9 int cost[28];
    10 
    11 int main() {
    12     int m, n;
    13     //freopen("input.txt","r",stdin);
    14     while(scanf("%d %d",&m,&n) != EOF) {
    15         scanf("%s",str);
    16         memset(cost, 0, sizeof(cost));
    17         for(int i = 0; i < m; i++) {
    18             int a, b;
    19             char c;
    20             cin >> c >> a >> b;
    21             cost[c-'a'] = min(a,b);
    22         }
    23         memset(dp, 0, sizeof(dp));
    24         for(int len = 1; len < n; len++) {
    25             for(int i = 0, j = len; i < n && j < n; i++,j++) {
    26                 if(str[i] == str[j]) {
    27                     dp[i][j] = dp[i+1][j-1];
    28                 }
    29                 else {
    30                     dp[i][j] = min(dp[i][j-1] + cost[str[j] - 'a'], dp[i+1][j] + cost[str[i] - 'a']);
    31                 }
    32             }
    33         }
    34         printf("%d
    ",dp[0][n-1]);
    35         
    36     }
    37     return 0;
    38 }
  • 相关阅读:
    flash/flex builder在IE中stage.stageWidth始终为0的解决办法
    “AS3.0高级动画编程”学习:第一章高级碰撞检测
    Flash/Flex学习笔记(57):实用技巧
    Flash/Flex学习笔记(56):矩阵变换
    flash开发中如何实现界面代码分离
    [转]Flash开发技能树
    flash builder代码格式化以及其它快捷键
    中小型商城系统中的分类/产品属性/扩展属性的数据库设计
    “AS3.0高级动画编程”学习:第四章 寻路(AStar/A星/A*)算法 (下)
    晒晒这两天做的播放器
  • 原文地址:https://www.cnblogs.com/jasonJie/p/5830629.html
Copyright © 2011-2022 走看看