01背包总结+传授个人经验

写在前面:

自从学了背包这个专题,感觉永远也写不完,之前写了三种类型的01背包,结果现在发现都是简单的01背包、后来又学了多重背包、完全背包,其中多重背包还可以进行二进制优化。

本文将对这几种常见的背包进行解释

另外,找到了一套OJ上比较不错的01背包专题,不是简单的签到题,但是也不是特别难

https://vjudge.net/contest/296080#problem/F

模块一:简单01背包

首先,如果你不知道什么是01背包,请先参考博客,补充相关知识

 

https://blog.csdn.net/xp731574722/article/details/70766804

 

那么,对于简单01背包,一共有三种写法,dp的分别有两种,dfs+剪枝的一种,分别对应不同的题目。

 

①普通写法,也是最简单的写法:

例题是HDU 2602

 Bone Collector

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14336    Accepted Submission(s): 5688

 

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

 

Source

HDU 1st “Vegetable-Birds Cup” Programming Open Contest

 

如果是才接触背包,请认真写题,然后理解

这里也简单说一下吧,普通的01背包,就是用 dp[vol]=value 表示vol体积这个状态下最大的价值value,然后不断更新,更新有两层for循环, 第一层是for循环1-n个物品,第二层是for循环1-bag_volume,循环背包的体积,当然这里第二层可以优化的写的,一般我们是for(背包的最大体积--该物体的体积),写好两层循环,就是状态转移dp[j] = max( dp[j],dp[j-vol]+val );  (vol表示当前物体体积,val表示当前物体价值,另外这里用的是空间优化的)

复杂度是 O(n*vol )n是物品个数,vol是背包容量。

第一种写法适用于n和vol都一般大( n是物体个数,vol是bag最大体积 ),差不多在1000,两者的乘积在可承受范围内(1e7)。

普通的我就不详细解释了

#include<iostream>
#include<cstdio>
#in
  • 12
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值