解题思路
朴素的多重背包,在朴素的完全背包的基础,加一个次数限制,即可
朴素做法:一个一个拆 $O(N)$
二进制优化:类似于快速幂的拆法 $O(logN)$,拆成多组
比如说:a 物品有 13 个
朴素做法就是一个一个的试,最终试到 13 个
二进制优化,则是拆成 5 组,{1, 2, 4, 8, 1} 尝试。因为由 {1, 2, 4, 8, 1} 这个集合里面的子集能凑 0 ~ 13 的任意一个数
代码
原始做法 O(N^3)
#include <iostream>
using namespace std;
const int N = 110;
int v[N], w[N], s[N], f[N][N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> v[i] >> w[i] >> s[i];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
for (int k = 0; j >= k * v[i] && k <= s[i]; k++) {
f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]);
}
}
}
cout << f[n][m] << endl;
return 0;
}
二进制优化 O(N^2logN)
#include <iostream>
using namespace std;
const int N = 10000;
int v[N], w[N], f[N][N];
int main() {
int n, m;
cin >> n >> m;
int cnt = 1;
for (int i = 1; i <= n; i++) {
int a, b, s;
cin >> a >> b >> s;
for (int k = 1; k <= s; s -= k, k <<= 1) {
v[cnt] = a * k, w[cnt] = b * k;
cnt++;
}
if (s) {
v[cnt] = a * s, w[cnt] = b * s;
cnt++;
}
}
n = cnt;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= v[i]) f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i]);
}
}
cout << f[n][m] << endl;
return 0;
}
在二进制优化上再优化空间
#include <iostream>
using namespace std;
const int N = 10000;
int v[N], w[N], f[N];
int main() {
int n, m;
cin >> n >> m;
int cnt = 1;
for (int i = 1; i <= n; i++) {
int a, b, s;
cin >> a >> b >> s;
for (int k = 1; k <= s; s -= k, k <<= 1) {
v[cnt] = a * k, w[cnt] = b * k;
cnt++;
}
if (s) {
v[cnt] = a * s, w[cnt] = b * s;
cnt++;
}
}
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]);
}
}
cout << f[m] << endl;
return 0;
}