其实所有的揹包问题都依赖于0/1揹包问题
0/1揹包问题(每个物品要么选要么不选)
- 揹包有上限Limit
- 有一些物品,每个有Cost,有Value
- 问最大的收益
举例子吧:
- Limit为8
- 物品1:cost=2,value=3
- 物品2:cost=3,value=4
- 物品3:cost=4,value=5
- 物品4:cost=5,value=6
解法是遍历物品,然后更新你的收获数组。直到遍历了所有的物品。那么你就得到了最终你的收获。
cost和value是第i个物品的花费和价值:则有:
f(i,v) = max { f(i-1,v) , f(i-1,v-cost) + value }
解释一下:你上限为v,可以挑选前i个物品。那么你的最大收益有两种情况:
- 我不选第i个物品。f(i-1,v)
- 我一定要选第i个物品。f(i-1,v-cost) + value
所以你要维护一个收益数组。然后遍历物品来跟新这个数组,直到遍历完物品。
维护数组的时候要从后向前维护,为什么呢,保证第i个物品,你只选择了一次。保证使用的f(i-1,v-cost)不掺杂第i个物品。(完全揹包问题是从前向后维护,这也是两者唯一不同点)
public class Demo11 {
public static void main(String[] args) {
int[][] list = new int[4][2];
list[0][0] = 2;
list[0][1] = 3;
list[1][0] = 3;
list[1][1] = 4;
list[2][0] = 4;
list[2][1] = 5;
list[3][0] = 5;
list[3][1] = 6;
int[] harvest = new int[9];
for (int i = 0; i < 4; i++) {
for (int j = 8; j >= 0; j--) {
int cost = list[i][0];
int value = list[i][1];
if (j - cost >= 0)
harvest[j] = Math.max(harvest[j], harvest[j - cost] + value);
}
}
System.out.println(harvest[8]);
}
}
分组揹包问题:其实就是0/1揹包问题。只不过现在的物品变成了一个组中的一个东西。
- 遍历组
- 维护收益数组
牛客网购物车问题
package May15;
import java.util.Scanner;
public class Demo10 {
public static class Good {
int cost;
int value;
public Good(int cost, int value) {
this.cost = cost;
this.value = value;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int money = in.nextInt();
int numToBuy = in.nextInt();
Good[][] arr = new Good[numToBuy][3];
for (int i = 1; i <= numToBuy; i++) {
int cost = in.nextInt();
int desire = in.nextInt();
int category = in.nextInt();
Good good = new Good(cost, cost * desire);
if (category == 0) {
arr[i - 1][0] = good;
} else {
if (arr[category - 1][1] != null) {
arr[category - 1][2] = good;
} else {
arr[category - 1][1] = good;
}
}
}
int[] harvest = new int[money + 1];
for (int j = 0; j < numToBuy; j++) {
if (arr[j][0] == null) {
continue;
}
for (int i = money; i >= 0; i--) {
Good master = arr[j][0];
if (i - master.cost >= 0)
harvest[i] = Math.max(harvest[i], harvest[i - master.cost] + master.value);
if (arr[j][1] != null) {
Good appendOne = arr[j][1];
if (i - master.cost - appendOne.cost >= 0) {
harvest[i] = Math.max(harvest[i], harvest[i - master.cost - appendOne.cost] + master.value + appendOne.value);
}
}
if (arr[j][2] != null) {
Good appendTwo = arr[j][2];
if (i - master.cost - appendTwo.cost >= 0) {
harvest[i] = Math.max(harvest[i], harvest[i - master.cost - appendTwo.cost] + master.value + appendTwo.value);
}
}
if (arr[j][1] != null && arr[j][2] != null) {
Good appendOne = arr[j][1];
Good appendTwo = arr[j][2];
if (i - master.cost - appendOne.cost - appendTwo.cost >= 0) {
harvest[i] = Math.max(harvest[i], harvest[i - master.cost - appendOne.cost - appendTwo.cost] + master.value + appendOne.value + appendTwo.value);
}
}
}
}
System.out.println(harvest[money]);
}
}
完全揹包问题:每个物品的数量没有限制
f(i,v) = max { f(i-1,v) , f(i-1,v-costk) + valuek } 【k为i物品的个数1,2,3,4…】
在代码上和0/1揹包问题。两者唯一的不同点在于,维护收益数组的方向不同。0/1揹包是从后向前维护。而完全揹包是从前向后维护。