题解 | #【模板】完全背包#
【模板】完全背包
http://www.nowcoder.com/practice/237ae40ea1e84d8980c1d5666d1c53bc
public class Main{
public static void main(String[] args) {
// 构造输入
Scanner sc = new Scanner(System.in);
// 01背包问题
// n 表示物品个数
int n = sc.nextInt();
// v 表示对应物品的体积
int v = sc.nextInt();
// n个物品对应的体积
int[] volume = new int[n+1];
// n个物品对应的价值
int[] wealth = new int[n+1];
// 1、将n个物品对应的体积和数组存入到对应数组中
for (int i = 1; i <= n; i++) {
volume[i] = sc.nextInt();
wealth[i] = sc.nextInt();
}
// init
int[] dp = new int[v + 1];
Arrays.fill(dp, Integer.MIN_VALUE);
dp[0] = 0;
// dp[i][j] = dp[i - 1][j], dp[i - 1][j - nums * v[i]] + num * w[i];
for (int i = 0; i <= v; i++) {
for (int j = 1; j <= n; j++) {
if (i >= volume[j]) {
dp[i] = Math.max(dp[i], dp[i - volume[j]] + wealth[j]);
}
}
}
int res = 0;
for (int i = 1; i <= v; i++) {
res = Math.max(res, dp[i]);
}
System.out.println(res);
System.out.println(Math.max(dp[v], 0));
}
}