解题思路
分组背包就是扩展了的 01 背包,状态转移与 01 一致。只是拓展了分组内物品的枚举
不做赘述,01 背包
代码
原始做法
#include <iostream>
using namespace std;
const int N = 110;
int v[N][N], w[N][N], s[N], f[N][N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> s[i];
for (int j = 1; j <= s[i]; j++) cin >> v[i][j] >> w[i][j];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
for (int k = 1; k <= s[i]; k++) {
if (j >= v[i][k]) f[i][j] = max(f[i][j], f[i - 1][j - v[i][k]] + w[i][k]);
}
}
}
cout << f[n][m] << endl;
return 0;
}
优化后
#include <iostream>
using namespace std;
const int N = 110;
int v[N][N], w[N][N], s[N], f[N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> s[i];
for (int j = 1; j <= s[i]; j++) cin >> v[i][j] >> w[i][j];
}
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 0; j--) {
for (int k = 1; k <= s[i]; k++) {
if (j >= v[i][k]) f[j] = max(f[j], f[j - v[i][k]] + w[i][k]);
}
}
}
cout << f[m] << endl;
return 0;
}