Dynamic Programming - 动态规划经典3题入门(LeetCode-198、HDU-2602、HDU-2084)

6 篇文章 0 订阅
1 篇文章 0 订阅

动态规划程序设计是对解最优化问题的一种途径、一种方法,而不是一种特殊算法。不像搜索或数值计算那样,具有一个标准的数学表达式和明确清晰的解题方法。动态规划程序设计往往是针对一种最优化问题,由于各种问题的性质不同,确定最优解的条件也互不相同,因而动态规划的设计方法对不同的问题,有各具特色的解题方法,而不存在一种万能的动态规划算法,可以解决各类最优化问题。因此读者在学习时,除了要对基本概念和方法正确理解外,必须具体问题具体分析处理,以丰富的想象力去建立模型,用创造性的技巧去求解。我们也可以通过对若干有代表性的问题的动态规划算法进行分析、讨论,逐渐学会并掌握这一设计方法。

适用条件
任何思想方法都有一定的局限性,超出了特定条件,它就失去了作用。同样,动态规划也并不是万能的。适用动态规划的问题必须满足最优化原理和无后效性。
1.最优化原理(最优子结构性质) 最优化原理可这样阐述:一个最优化策略具有这样的性质,不论过去状态和决策如何,对前面的决策所形成的状态而言,余下的诸决策必须构成最优策略。简而言之,一个最优化策略的子策略总是最优的。一个问题满足最优化原理又称其具有最优子结构性质。
2.无后效性将各阶段按照一定的次序排列好之后,对于某个给定的阶段状态,它以前各阶段的状态无法直接影响它未来的决策,而只能通过当前的这个状态。换句话说,每个状态都是过去历史的一个完整总结。这就是无后向性,又称为无后效性。
3.子问题的重叠性 动态规划将原来具有指数级时间复杂度的搜索算法改进成了具有多项式时间复杂度的算法。其中的关键在于解决冗余,这是动态规划算法的根本目的。动态规划实质上是一种以空间换时间的技术,它在实现的过程中,不得不存储产生过程中的各种状态,所以它的空间复杂度要大于其它的算法。

一维DP:自顶向下顺推
https://leetcode.com/problems/house-robber/

LeetCode-198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

class Solution {
public:
    int rob(vector<int>& dp) {
        if(dp.size()<1)
            return 0;
        for(int i=0;i<dp.size();i++){
            if(i==0) dp[i]=dp[0];
            else if(i==1) dp[i]=max(dp[0],dp[1]);
            else dp[i]=max(dp[i-1],dp[i-2]+dp[i]);
        }
        return dp[dp.size()-1];
    }
};

第一次使用LeetCode提交,对环境不熟悉,记录一下这个Bug
LeetCode – reference binding to null pointer of type ‘value_type’
//如果没有加上这个判断条件,在输入空数组的时候就会报如题错误
//所以要对各种情况考虑周全
if(nums.size()<1)
return 0;


二维DP:自底向上递推

http://acm.hdu.edu.cn/showproblem.php?pid=2084

在讲述DP算法的时候,一个经典的例子就是数塔问题,它是这样描述的:

有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少?

已经告诉你了,这是个DP的题目,你能AC吗?

Input
输入数据首先包括一个整数C,表示测试实例的个数,每个测试实例的第一行是一个整数N(1 <= N <= 100),表示数塔的高度,接下来用N行数字表示数塔,其中第i行有个i个整数,且所有的整数均在区间[0,99]内。
在这里插入图片描述

Output
对于每个测试实例,输出可能得到的最大和,每个实例的输出占一行。

Sample Input
1
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

Sample Output
30

#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int i,j;
    int dp[101][101];
    int c,n;
    cin >> c;
    while(c--)
    {
        cin >> n;
        
        for(i=1;i<=n;i++)
            for(j=1;j<=i;j++)
            	cin >> dp[i][j];
            	            
        for(i=n-1;i>=1;i--)
            for(j=1;j<=i+1;j++)
                dp[i][j]=max(dp[i][j]+dp[i+1][j],dp[i][j]+dp[i+1][j+1]);

        cout << dp[1][1] << endl;
    }    
    return 0;
}


01背包问题

http://acm.hdu.edu.cn/showproblem.php?pid=2602

Bone Collector
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 94659 Accepted Submission(s): 38697

Problem Description
Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?

Input
The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output
One integer per line representing the maximum of the total value (this number will be less than 231).

Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1

Sample Output

14

#include <iostream>
using namespace std;

const int MAX = 1001;
int dp[MAX][MAX]={0};
struct bones {
    int v,w;
};

int main()
{
    int n,i,j,N,V;
    cin >> n;
    while(n--)
    {
        cin >> N >> V;
        struct bones arr[N]={0};;
        for(i=1;i<=N;i++)
            cin >> arr[i].v;
        for(i=1;i<=N;i++)
            cin >> arr[i].w;
        for(i=1;i<=N;i++)
            for(j=0;j<=V;j++)
                if(arr[i].w<=j)
                    dp[i][j]=max(dp[i-1][j] , dp[i-1][j-arr[i].w]+arr[i].v);
                else
                    dp[i][j]=dp[i-1][j];
            cout << dp[N][V] <<endl;
    }
    return 0;
}


01背包最关键的一步:
		for(i=1;i<=N;i++)
        for(j=0;j<=V;j++)
            if(arr[i].w<=j)
                dp[i][j]=max(dp[i-1][j] , dp[i-1][j-arr[i].w]+arr[i].v);
            else
                dp[i][j]=dp[i-1][j];
这里类似于一个二维数组,数组dp[i][j]:i为前i个物品,j为剩下的空间
这里是遍历所有的骨头
for(i=1;i<=N;i++)
这里是逐步增加一个临时变量j的重量,并且j的重量不超过背包的负重
for(j=0;j<=V;j++)
第一种情况:当骨头的重量小于j时
if(arr[i].w<=j)
比较取第i件与不取i-1件的价值
dp[i][j]=max(dp[i-1][j] , dp[i-1][j-arr[i].w]+arr[i].v);
第二种情况:当第i件太重时,不能选第i件
else
dp[i][j]=dp[i-1][j];
最后输出最后一个dp[i][j]即为所求值

总结一下:

DP可分为一维、二维与背包
DP可用递归、备忘录、自底向上方法解决
DP最重要的思想:最优子结构、重叠子问题

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值