package com.dongtaiguihua;
import java.util.Arrays;
//多重背包问题
//有n种物品,物品的价值为 w = {3, 4, 5};对应的重量v = {2, 3, 4},每种物品的数量m = {4, 3, 2},背包的容量为c = 15,计算包最多装物品的价值?(每个物品可取个数有限制)
public class PackageMulti {
public static void main(String[] args) {
int[] w = {3, 4, 5};//重量
int[] v = {2, 3, 4};//价值
int[] m = {4, 3, 2};//数量
int c = 15;//容量
System.out.println(getPackageMaxValue01(w, v, m, c));
}
public static int getPackageMaxValue01(int[] w, int[] v, int[] m, int C) {//优化空间
int size = w.length;
int[] dp = new int[C + 1];
//初始化第一行
//仅考虑容量为C的背包放第0个物品的情况,物品从0开始
for (int i = 0; i <= C; i++) {
for (int k = 0; k <= m[0] && k * w[0] <= i; k++) {//比完全背包多了m[i]的限制
dp[i] = k * v[0];
}
}
System.out.println(Arrays.toString(dp));
//填充其他行和列
for (int i = 1; i < size; i++) {//从1号物品遍历
for (int j = C; j > 0; j--) {
for (int k = 1; k <= m[i] && k * w[i] <= j; k++) {//比完全背包多了m[i]的限制
if (dp[j - k * w[i]] + k * v[i] > dp[j]) {
dp[j] = dp[j - k * w[i]] + k * v[i];
}
}
}
System.out.println(Arrays.toString(dp));
}
return dp[C];
}
}
12-26
11-17
11-17