多重背包
每件物品的个数有限制
朴素算法
与完全背包的朴素算法类似 时间复杂度O ( N ∗ V ∗ S )
优化成一维时需要从大到小枚举j
for (int i = 1;i <= n;++i) { for (int j = 0;j <= m;++j) { for (int k = 0;k * v[i] <= j && k <= s[i];++k) { f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]); } } }
二进制优化
int cnt = 0; for (int i = 1;i <= n;++i) { int a, b, s; cin >> a >> b >> s; int k = 1; while (k <= s) { cnt++; v[cnt] = a * k; w[cnt] = b * k; s -= k; k *= 2; } if (s > 0) { ++cnt; v[cnt] = a * s; w[cnt] = b * s; } } n = cnt; for (int i = 1; i <= n;++i) { for (int j = m;j >= v[i];--j) { f[j] = max(f[j], f[j - v[i]] + w[i]); } }