有
N
种物品和一个容量为
V
的背包,每种物品都有无限件可用。放入第
i
种
物品的费用是 C i ,价值是 W i 。求解:将哪些物品装入背包,可使这些物品的耗
物品的费用是 C i ,价值是 W i 。求解:将哪些物品装入背包,可使这些物品的耗
费的费用总和不超过背包容量,且价值总和最大。
import java.util.ArrayList;
public class entireBagProblem {
static class Item {//表
int totalValue = 0;//每一项的总价值
ArrayList<Integer> itemLink = new ArrayList<>();//用于该项有哪几样物品
}
static ArrayList<Integer> solve1(int[] price, int[] weigh, int v) {
int len = price.length;
Item[] table = new Item[v + 1];
//初始化表
for (int i = 0; i <= v; i++) {
table[i] = new Item();
}
for (int i = 0; i < len; i++) {
for (int j = weigh[i]; j <= v; j++) {
int result2 = table[j - weigh[i]].totalValue;//F [v]
int result1 = table[j].totalValue;//F[v-Wi]
if(result1 < result2 + price[i]){
table[j].totalValue = result2+price[i];
table[j].itemLink.clear();
table[j].itemLink.addAll(table[j - weigh[i]].itemLink);
table[j].itemLink.add(i+1);
}
}
}
return table[v].itemLink;
}
public static void main(String[] args) {
int[] v = {8, 10, 6, 3, 7, 2};
int[] w = {4, 6, 2, 2, 5, 1};
System.out.println(solve1(v, w, 12));
}
}