分组背包二进制优化
P1776
前言
下文设
参考 这篇文章。
思想
考虑我们分组背包的时候需要枚举选几个,这是
例如:
这样我们可以把
Code
#include <bits/stdc++.h>
using namespace std;
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
const int N = 1e2 + 10, M = 1e5 + 10;
int w[N << 5], v[N << 5], n, m, f[M], cnt;
int main()
{
fst
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
int _v, _w, c;
cin >> _v >> _w >> c;
for (int j = 0; (1 << j) <= c; j++) v[++cnt] = _v * (1 << j), w[cnt] = _w * (1 << j), c -= (1 << j);
if (c) v[++cnt] = _v * c, w[cnt] = _w * c;
}
for (int i = 1; i <= cnt; i++) for (int j = m; j >= w[i]; j--) f[j] = max(f[j], f[j - w[i]] + v[i]);
cout << f[m];
return 0;
}