01背包问题
用动态规划算法实现 0-1 背包问题,在计算机上编程实现。我们有 n 种物品,物品 j 的重量为 wj,价格为 pj。我们假定所有物品的重量和价格都是非负的。背包所能承受的最大重量为 c。如果限定每种物品只能选择 0 个或 1 个。 有六件物品,体积和价值见下表,背包容量为 25。
| i | 1 2 3 4 5 6 |
| w(体积) | 11 7 9 12 3 10 |
| v(价值) | 10 5 7 9 2 12 |
求解的思想:
- 背包容量不足以放下第 i 件物品,只能选择不拿:m[ i ][ j ] = m[ i-1 ][ j ]
- 背包容量可以放下第 i 件物品,我们就要考虑拿这件物品是否能获取更大的价值。
- 综合以上两种情况可以得到状态转换方程 :
f[i,j]=Max{ f[i-1,j-Wi]+Vi( j >= Wi ),f[i-1,j]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72public class Zero_one {
public int packageweight = 25;//背包的总容量
public int productnum = 6;//物品总数
public int[] weights = {11, 7, 9, 12, 3, 10};//每个物品的重量
public int[] values = {10, 5, 7, 9, 2, 12};//每个物品的价值
public static void main(String[] args) {
Zero_one zero_one = new Zero_one();
int[][] m = zero_one.initpkdata();
int[][] res = zero_one.result(m);
System.out.println("输出:");
System.out.println("最大价值:" + res[zero_one.productnum][zero_one.packageweight]);
System.out.print("装入的物品编号是:");
zero_one.findproducts(res);
}
/**
* 初始化背包
* m[i][0] = 0 :表示背包重量为0,不能装东西,因此价值全为0
* m[0][j] = 0 :表示没有可以装的物品,因此价值为0
*/
public int[][] initpkdata() {
int[][] m = new int[this.productnum + 1][this.packageweight + 1];
for (int i = 0; i <= this.productnum; i++) {
m[i][0] = 0;
}
for (int j = 0; j <= this.packageweight; j++) {
m[0][j] = 0;
}
return m;
}
public int[][] result(int[][] arr) {
for (int i = 1; i <= this.productnum; i++) {
for (int j = 1; j <= this.packageweight; j++) {
// 当第i件物品重量大于当前包的容量 则放不进去
// 所以当前背包所含价值等于前i-1件商品的价值
if (this.weights[i - 1] > j) {
arr[i][j] = arr[i - 1][j];
}
/*当第i件物品能放进去时
1 放入物品,价值为:arr[i-1][j-(int)this.weights.get(i-1)] + (int)this.values.get(i-1)
2不放入物品,价值为前i-1件物品价值和:arr[i][j] = arr[i-1][j];
此时最大价值为上述两种方案中最大的一个
*/
else {
if (arr[i - 1][j] < arr[i - 1][j - this.weights[i - 1]] + this.values[i - 1]) {
arr[i][j] = arr[i - 1][j - this.weights[i - 1]] + this.values[i - 1];
} else {
arr[i][j] = arr[i - 1][j];
}
}
}
}
return arr;
}
public void findproducts(int[][] arr) {
int j = this.packageweight;
for (int i = 1; i <= this.productnum; i++) {
if (arr[i][j] > arr[i - 1][j]) {
System.out.print(i + ",");//输出选中的物品的编号
j = j - this.weights[i - 1];
if (j < 0) {
break;
}
}
}
}
}