Files
python/TangDou/AcWing/BeiBao/7.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

46 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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 * 31];
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;
}