0 1 knapsack problem
01 Backpack (Zeroonepack): there are n items and a backpack with a capacity of V. ( only one piece per item ) The cost of item I is c[i] and the value is w[i]. The sum of the values is maximized by solving which items are loaded into the backpack.
TopicsThere are n items and a backpack with a capacity of V. The cost of article I is c[i], the value is w[i]. The sum of the values is maximized by solving which items are loaded into the backpack.
Basic IdeasThis is the most basic knapsack problem, characterized by: only one piece of each item, you can choose to put or not put. Define the state with sub-question: F[i][v] Indicates the maximum value that the first I item can get in a backpack with a capacity of V. The state transfer equation is:F[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]}
Initialize: f?0for (I=1 to N) {for (j=1 to V) { f[i][j]=f[i-1][j]; if (J>=c[i]) { f[i][j]=max{f[i-1][j], F[i-1][j-c[i]]+w[i]}; } }}
第一种是第i件不放进去,这时所得价值为:f[i-1][v]
第二种是第i件放进去,这时所得价值为:f[i-1][v-c[i]]+w[i]
最后比较第一种与第二种所得价值的大小,哪种相对大,f[i][v]的值就是哪种。
Use the table to illustrate:
| back containment |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
1 0 |
1 1 |
1 2 |
1 3 |
1 4 |
1 5 |
| 5 Items |
0 |
0 |
0 |
0 |
0 |
0 |
6 |
12 |
12 |
15 |
15 |
18 |
22 |
22 |
25 |
25 |
| 4 Items |
0 |
0 |
3 |
3 |
3 |
3 |
3 |
12 |
12 |
15 |
15 |
18 |
22 |
22 |
25 |
25 |
| 3 Items |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
12 |
12 |
15 |
15 |
15 |
22 |
22 |
22 |
22 |
| 2 Items |
0 |
0 |
0 |
0 |
3 |
12 |
12 |
12 |
12 |
15 |
15 |
15 |
15 |
15 |
15 |
15 |
| 1 Items |
0 |
0 |
0 |
0 |
0 |
12 |
12 |
12 |
12 |
12 |
12 |
12 |
12 |
12 |
12 |
12 |
Examples:5 items, (weight, value) are: (5,a), (4, 3), (7,ten), (2, 3 ), ( 6 , 6 ) The backpack has a capacity of Code:
#include <stdio.h> #include <string.h> #include <algorithm>using namespace Std;int main () {int f[6][16 ];int cos[6]={0,5,4,7,2,6};int Val[6]={0,12,3,10,3,6};memset (f,0,sizeof (f)); for (int. i=1;i<=5;i++) {for (int j=1;j <=15;j++) {f[i][j]=f[i-1][j];if (J>=cos[i]) {F[i][j]=max (f[i-1][j],f[i-1][j-cos[i]]+val[i]);}}} for (int i=1;i<=5;i++) {for (int j=1;j<=15;j++) printf ("%d", f[i][j]);
this is stored in a two-bit array that optimizes space and stores it with one array! Code:
Optimization: Convert f array to one-dimensional array #include<stdio.h> #include <string.h> #include <algorithm>using namespace Std;int Main () {int f[16];int cos[6]={0,5,4,7,2,6};int val[6]={0,12,3,10,3,6};memset (f,0,sizeof (f)); for (int i=1;i<=5;i++ {for (int j=15;j>=1;j--) {if (J>=cos[i]) {F[j]=max (f[j],f[j-cos[i]]+val[i]);}}} for (int i=1;i<=15;i++) {
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
01 knapsack problem