完全背包只需要在01基础上把体积改成顺着过一遍,就可以了。
import java.io.*;
class Main{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int n, m;
static int N = 1010;
static int w[] = new int[N], v[] = new int[N], f[] = new int[N];
public static void main(String[] args) throws IOException {
String[] s = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
for (int i = 1 ; i <= n ; i++) {
s = br.readLine().split(" ");
w[i] = Integer.parseInt(s[0]);
v[i] = Integer.parseInt(s[1]);
}
for (int i = 1; i <= n; i++)
for (int j = 0; j <= m; j++)
if (j >= w[i])
f[j] = Math.max(f[j], f[j - w[i]] + v[i]);
pw.println(f[m]);
pw.flush();
pw.close();
br.close();
}
}
本文详细介绍了解决完全背包问题的方法,通过调整01背包算法中物品体积的处理方式,实现对无限数量相同物品的选择优化。提供了Java代码实现,包括输入解析、状态转移方程及输出结果的全过程。
485

被折叠的 条评论
为什么被折叠?



