朴素版本
#include<iostream>
using namespace std;
const int N = 110;
int n, m, f[N][N], v[N][N], w[N][N], s[N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> s[i];
for (int k = 0; k < s[i]; k++) {
cin >> v[i][k] >> w[i][k];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) {
f[i][j] = f[i - 1][j];
for (int k = 0; 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;
}
一维优化
j from m to 0
#include<iostream>
using namespace std;
const int N = 1010;
int n, m, f[N], v[N][N], w[N][N], s[N];
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> s[i];
for (int k = 0; k < s[i]; k++)
cin >> v[i][k] >> w[i][k];
}
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 0; j--) {
for (int k = 0; 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];
}