其實所有的揹包問題都依賴於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揹包是從後向前維護。而完全揹包是從前向後維護。