AcWing 4. 【Java】多重背包问题 I
原题链接
简单
作者:
tt2767
,
2020-01-12 00:27:01
,
所有人可见
,
阅读 2174
/*
1. 状态定义: 已经选了1...i种物品且背包体积 <=j 时的最大值 -> 优化为f[j]
2. 状态计算: 以最后一次选i划分为选还是不选,根据遍历体积转化为选几次 即 f[j] = MAX (f[j - k* v[i]] + k*w[i] )
3. 边界:f[~] = 0
*/
import java.util.*;
public class Main{
void run(){
int n = jin.nextInt();
int m = jin.nextInt();
for (int i = 1 ; i <= n ; i++) {
v[i] = jin.nextInt();
w[i] = jin.nextInt();
s[i] = jin.nextInt();
}
int res = dp(n, m);
System.out.println(res);
}
int dp(int n, int m){
int[] f = new int[maxN];
for (int i = 1 ; i <= n ;i ++){
for (int j = m ; j >= v[i] ; j--){
for (int k = 0 ; k <= s[i] && k* v[i] <= j ;k++){
// 把最简单的完全背包改写下
f[j] = Math.max(f[j], f[j - k* v[i]] + k* w[i]);
}
}
}
return f[m];
}
int maxN = 1002;
int[] v = new int[maxN];
int[] w = new int[maxN];
int[] s = new int[maxN];
Scanner jin = new Scanner(System.in);
public static void main(String[] args) {new Main().run();}
}
改写的是0-1背包吗,完全背包是正序的呀