题目描述:
有N种物品,每种物品的数量为C1,C2......Cn。从中任选若干件放在容量为W的背包里,每种物品的体积为W1,W2......Wn(Wi为整数),与之相对应的价值为P1,P2......Pn(Pi为整数)。求背包能够容纳的最大价值。
输入
第1行,2个整数,N和W中间用空格隔开。N为物品的种类,W为背包的容量。(1 <= N <= 100,1 <= W <= 50000)
第2 - N + 1行,每行3个整数,Wi,Pi和Ci分别是物品体积、价值和数量。(1 <= Wi, Pi <= 10000, 1 <= Ci <= 200)
输出
输出可以容纳的最大价值。
输入示例
3 6
2 2 5
3 3 8
1 4 1
输出示例
9
import java.util.Scanner;
public class MultiplePack {
static int[] c;
static int[] v;
static int[] a;
static int[] f;
static int N;
static int V;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
N = scanner.nextInt();
V = scanner.nextInt();
c = new int[105];
v = new int[105];
a = new int[105];
for(int i = 0; i < N; i++) {
c[i] = scanner.nextInt();
v[i] = scanner.nextInt();
a[i] = scanner.nextInt();
}
f = new int[V+1];
for(int i = 0; i < N; i++) {
multiplePack(c[i], v[i], a[i]);
}
System.out.println(f[V]);
}
public static void multiplePack(int cost,int weight,int amount) {
if(cost * amount >= V) {
completePack(cost, weight);
return;
}
int k = 1;
while(k < amount) {
zeroOnePack(k * cost, k * weight);
amount -= k;
k *= 2;
}
zeroOnePack(amount * cost, amount * weight);
}
public static void completePack(int cost,int weight) {
for(int j = cost; j <= V; j++) {
f[j] = Math.max(f[j], f[j-cost] + weight);
}
}
public static void zeroOnePack(int cost,int weight) {
for(int j = V; j >= cost; j--) {
f[j] = Math.max(f[j], f[j-cost] + weight);
}
}
}