朴素版代码
import java.util.*;
import java.io.*;
public class Main {
static int N = 110;
static int[] v = new int[N];
static int[] w = new int[N];
static int[] s = new int[N];
static int[][] f = new int[N][N];
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n = sc.nextInt();
int m = sc.nextInt();
for (int i = 1; i <= n; i ++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
s[i] = sc.nextInt();
}
for (int i = 1; i <= n; i ++) {
for (int j = 0; j <= m; j ++) {
for (int k = 0; k <= s[i] && k * v[i] <= j; k ++) {
f[i][j] = Math.max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]);
}
}
}
System.out.println(f[n][m]);
sc.close();
}
}
优化版代码
二进制优化原理见 多重背包问题-二进制优化题解
import java.util.*;
import java.io.*;
public class Main {
// N = N * logS = 110 * log100 ≈ 710
static int N = 710;
static int[] v = new int[N];
static int[] w = new int[N];
static int[] f = new int[M];
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n = sc.nextInt();
int m = sc.nextInt();
// 打包分组下标
int k = 0;
// 对每一种物品进行分组打包,
for (int i = 1; i <= n; i ++) {
// 第 i 种物品信息(体积,价值,数量)
int vi = sc.nextInt();
int wi = sc.nextInt();
int s = sc.nextInt();
// 打包分组的数量
int cnt = 1;
// 只要可分组数量还未超过 s,就按照 2^k 打包
while (cnt <= s) {
k ++;
// 分组物品的体积 = 当前分组数量 * 物品体积
v[k] = cnt * vi;
// 分组物品价值 = 当前分组数量 * 物品价值
w[k] = cnt * wi;
// 当前物品数量 - 已分组的物品数量
s -= cnt;
// 分组数量 * 2
cnt *= 2;
}
// 如果可分组数量 cnt < s,并且 s > 0,说明有剩余物品未打包,需要再次打包
if (s > 0) {
k ++;
v[k] = s * vi;
w[k] = s * wi;
}
}
// 对每一个分组进行01背包求解
for (int i = 1; i <= k; i ++) {
for (int j = m; j >= v[i]; j --) {
f[j] = Math.max(f[j], f[j - v[i]] + w[i]);
}
}
System.out.println(f[m]);
sc.close();
}
}