二维dp:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
//输入物品种类N和容量V
Scanner reader = new Scanner(System.in);
int N = reader.nextInt();
int V = reader.nextInt();
//定义3个一维数组:表示每个物品体积v,价值w,最多件数s
int[] v = new int[N + 1];
int[] w = new int[N + 1];
int[] s = new int[N + 1];
for(int i = 1; i <= N; i++){
v[i] = reader.nextInt();
w[i] = reader.nextInt();
s[i] = reader.nextInt();
}
reader.close();
//二维DP
int[][] dp = new int[N + 1][V + 1];
dp[0][0] = 0;//前0个物品总体积为0时,最大价值为0
for(int i = 1; i <= N; i++){
for(int j = V; j >= 0; j--){
for(int k = 0; k <= s[i] && k *v[i] <= j; k++){
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * v[i]] + k * w[i]);
}
}
}
System.out.println(dp[N][V]);//返回前N个物品体积为V时的最大价值
}
}
一维–优化后
import java.util.Scanner;
public class Main{
public static void main(String[] args){
//输入物品种类N和容量V
Scanner reader = new Scanner(System.in);
int N = reader.nextInt();
int V = reader.nextInt();
//定义3个一维数组:表示每个物品体积v,价值w,最多件数s
int[] v = new int[N + 1];
int[] w = new int[N + 1];
int[] s = new int[N + 1];
for(int i = 1; i <= N; i++){
v[i] = reader.nextInt();
w[i] = reader.nextInt();
s[i] = reader.nextInt();
}
reader.close();
//f[j]:表示体积为j时的最大价值
int[] dp = new int[V + 1];
dp[0] = 0;//总体积为0时,最大价值为0
for(int i = 1; i <= N; i++){
for(int j = V; j >= 0; j--){
for(int k = 0; k <= s[i] && k *v[i] <= j; k++){
dp[j] = Math.max(dp[j], dp[j - k * v[i]] + k * w[i]);
}
}
}
System.out.println(dp[V]);//返回体积为V时的最大价值
}
}