You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.2 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n; // 物品种类
int m; // 背包容量
int f[N]; // dp数组
int idx;
struct Node {
int v, w;
} c[N * 12];
int main() {
cin >> n >> m;
// 二进制打包
for (int i = 1; i <= n; i++) {
// 体积,价值,个数
int v, w, s;
cin >> v >> w >> s;
// 根据题意做一些小的变形
if (s == -1)
s = 1; // 题目中s=-1表示只有1个
else if (s == 0)
s = m / v; // 完全背包(其实本质上就是多重背包):最多总体积/该物品体积向下取整
// 如果是其它大于0的数字那么是多重背包
// 将完全背包和多重背包利用二进制优化转化为01背包
for (int j = 1; j <= s; j *= 2) {
c[++idx] = {j * v, j * w};
s -= j;
}
// 不够下一个2^n时独立成包
if (s) c[++idx] = {s * v, s * w};
}
// 01背包
for (int i = 1; i <= idx; i++)
for (int j = m; j >= c[i].v; j--)
f[j] = max(f[j], f[j - c[i].v] + c[i].w);
// 输出
printf("%d\n", f[m]);
return 0;
}