当前位置:网站首页>Dynamic programming-01 knapsack problem
Dynamic programming-01 knapsack problem
2022-07-24 02:43:00 【Caterpillars who want to write programs】
------ Use java To write , Logically, all languages are common
One 、 What is? 01 knapsack
(1) Concept
01 The knapsack problem is M Take out several items and put them in the space for W In my backpack , The weight of each item is wight1 , wight2 to wightn , The corresponding value is money1 , money2 to moneyn ;
01 The constraint of knapsack is to give several items , There is only one item of each kind , Judge the value of items that can be put into the backpack to the maximum extent that it can bear ;
Two 、 How to understand the knapsack problem
(1) Example :
There is one 1 kg Value is 15 Yuan's apple 、 One 3 kg Value is 20 Cantaloupe of Yuan 、 One 4kg Value is 30 Durian of Yuan , Use a bearing capacity of 4 kg The backpack , Ask how much fruit the backpack can hold with a maximum value of ?
(2) List comprehension
2.1
According to the example , Assume the following table , Namely ownership 0 - 3 Kind of fruit 、0 - 4 kg Heavy 5 When a backpack , Ask the maximum value of fruit in it ;
( Join in Do not load fruit and 0 kg The situation is to align the number of fruits and the weight of the backpack with the coordinates , Don't join )
| 0kg | 1kg | 2kg | 3kg | 4kg | |
| Do not load :0kg 0 element | |||||
| Apple :1kg 15 element | |||||
| Hami melon :3kg 20 element | |||||
| durian :4kg 30 element |
2.2
Whether it's 0 kg The ultimate value of the backpack without fruit is 0 element , Therefore, these two cases are directly filled as 0 element ;
| 0kg | 1kg | 2kg | 3kg | 4kg | |
| Do not load :0kg 0 element | 0 element | 0 element | 0 element | 0 element | 0 element |
| Apple :1kg 15 element | 0 element | ||||
| Hami melon :3kg 20 element | 0 element | ||||
| durian :4kg 30 element | 0 element |
2.3
When there is only one apple ,1 - 4 kg How much fruit can you put in your backpack ;
Because there is only one apple , and 1 kg Apple of 1 - 4 kg Can be put into , So when there is only one apple 1 - 4 kg My backpacks are 15 element ;
| 0kg | 1kg | 2kg | 3kg | 4kg | |
| Do not load :0kg 0 element | 0 element | 0 element | 0 element | 0 element | 0 element |
| Apple :1kg 15 element | 0 element | 15 element | 15 element | 15 element | 15 element |
| Hami melon :3kg 20 element | 0 element | ||||
| durian :4kg 30 element | 0 element |
2.4
Calculate when you have apple and cantaloupe ,1 - 4 kg How much fruit can you put in your backpack ;
Because Hami melon is 3 kg so 1 kg and 2 kg Only apples can be put into the heavy backpack , Therefore, the value obtained when there is only apple in the previous line is introduced ;
When the conditions for putting Hami melon are met , There may be two situations for the value of fruit that can be put :
1. Without Hami melon, it is the maximum value of fruit that can be put under the current weight ;
2. Put in a Hami melon , Then calculate the remaining space , Plus the maximum value that the remaining weight can fit without Hami melon ;( Because a Hami melon has been put in , There is no second cantaloupe )
find 1 、2 Among them, the greater fruit value , It is the maximum value that the current backpack can contain fruit ;
Therefore, this formula is derived :( Max() It means taking a larger value )
Max( The value of the fruit stored in the previous row of the current weight , The current value of fruit + The fruit value of the remaining space in the previous line )
| 0kg | 1kg | 2kg | 3kg | 4kg | |
| Do not load :0kg 0 element | 0 element | 0 element | 0 element | 0 element | 0 element |
| Apple :1kg 15 element | 0 element | 15 element | 15 element | 15 element | 15 element |
| Hami melon :3kg 20 element | 0 element | 15 element | 15 element | 20 element | 35 element |
| durian :4kg 30 element | 0 element |
2.5
Use the deduced formula to fill in the table with durian ;
| 0kg | 1kg | 2kg | 3kg | 4kg | |
| Do not load :0kg 0 element | 0 element | 0 element | 0 element | 0 element | 0 element |
| Apple :1kg 15 element | 0 element | 15 element | 15 element | 15 element | 15 element |
| Hami melon :3kg 20 element | 0 element | 15 element | 15 element | 20 element | 35 element |
| durian :4kg 30 element | 0 element | 15 element | 15 element | 20 element | 35 element |
(2) Code demonstration
2.1
Create three arrays according to the above method , A storage fruit weight , The value of a stored fruit , A maximum value of the fruit in the backpack in each case , Don't miss the situation when the fruit is not loaded ;
Weight and value can be directly filled in according to the table , A binary array bag Take the number of fruits in the row , Then take the length of any array directly , Because the weight of the backpack is 4 kg , Therefore, the total number of columns should be 0 - 4 total 5 A place ;

2.2
Because when the weight is less than or equal to the storage capacity of the backpack, the formula is Max( The value of the fruit stored in the previous row of the current weight , The current value of fruit + The fruit value of the remaining space in the previous line ) , Therefore, several currently defined arrays are substituted into this formula to get :
bag[i][j] = Math.max( bag[i-1][j] , money[i] + bag[i-1][j-wight[i]] );Use the formula to traverse the entire array ;

2.3
Finally, the answer to the question is obtained by outputting the lower right element of the array ;

3、 ... and 、 Code sharing
public class DP_01Bag {
public static void main(String[] args) {
int[] wight = { 0 , 1 , 3 , 4 };
int[] money = { 0 , 15 , 20 , 35 };
int[][] bag = new int[wight.length][5];
for (int i = 1; i < bag.length; i++) {
for (int j = 1; j < bag[i].length; j++) {
if ( wight[i] > j)
bag[i][j] = bag[i-1][j];
else bag[i][j] = Math.max( bag[i-1][j] , money[i] + bag[i-1][j-wight[i]] );
}
}
System.out.println( bag[bag.length-1][bag[0].length-1] );
}
}
边栏推荐
- SSM的技术论坛含前后台
- This article shows you how to use SQL to process weekly report data
- Analyze the space practice field required by maker education activities
- compostion-api(setup中) watch使用细节
- SSM家庭理财个人理财管理系统记账系统
- 如何获取步态能量图gei
- Mysql数据库,分组函数篇
- 通用机环境下安全版单机数据库使用非root用户管理的解决方案
- 微信小程序实现折线面积图-玫瑰图-立体柱状图
- 攻防世界WEB練習區(view_source、get_post、robots)
猜你喜欢

Recorded on July 21, 2022
![[interview: concurrent Article 21: multithreading: activeness] deadlock, livelock, hunger](/img/35/c5f2f8da185d0553c6244d6e4c1216.png)
[interview: concurrent Article 21: multithreading: activeness] deadlock, livelock, hunger

Leetcode exercise -- two questions about the nearest common ancestor of binary trees

Share an API Gateway project based on ABP and yarp

"Why should we do IVX?"—— Interview with IVX CEO Meng Zhiping to understand IVX corporate culture

TP5 framework link promotion project

Job hunting and recruitment system of SSM part-time job hunting

关于 SAP 电商云 Spartacus UI Transfer State 冗余 API 请求发送的讨论
![[datasets] - downloading some datasets of flyingthings3d optical flow](/img/00/5d87b378ebab49e9dc400d8e3634f3.png)
[datasets] - downloading some datasets of flyingthings3d optical flow

理解加载class到JVM的时机
随机推荐
Composition API (in setup) watch usage details
“我们为什么要做 iVX ? ” ——访 iVX CEO 孟智平 了解 iVX 企业文化
Recorded on July 21, 2022
Zone d'entraînement Web d'attaque et de défense (View source, get Post, robots)
Essential skills for programmers -- breakpoint debugging (idea version)
Qt开发串口通讯软件中的数据转换问题:读取时_QByteArray转string;发送时_数据格式;int转16进制格式string;string中截取字符;16进制数加法;string转ByteAr
无需编码,自动实现“异步 Request-Reply”模式
Doodle icons - a free commercial graffiti style icon library, cute, light and unique
C language actual combat guessing game
Vscade connects to the server. The password is correct, but it has been unable to connect
Mysql数据库,排序与单行处理函数篇
Liveqing live RTMP on demand video streaming platform how to carry the Sid and token returned by the login interface to call authentication streamtoken video streaming authentication
Custom log annotation, request fetching
Cloud native explanation [expansion]
Data conversion problem in Qt development serial communication software: when reading_ Qbytearray to string; When sending_ Data format; Int to hexadecimal format string; Intercept characters in string
中城院真的在帮助供应商解决问题吗?
No coding is required, and the "asynchronous request reply" mode is automatically implemented
Unity timeline tutorial
【补题日记】[2022牛客暑期多校2]K-Link with Bracket Sequence I
Chinese scientists have made new progress in high security quantum key distribution networks