二维
/*
f[i][j] = max(f[i - 1][j], f[i - 1][j - v[i][k]] + w[i][k])
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m;
int v[N][N], w[N][N],s[N];
int f[N][N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
cin >> s[i];
for (int j = 0; j < s[i]; j ++ )
{
cin >> v[i][j] >> w[i][j];
}
}
for (int i = 1; i <= n; i ++ )
for (int j = 0; j <= m; j ++ )
{
f[i][j] = f[i - 1][j];//第i组物品一个都不选
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;
}
优化f[m]
/*
f[i][j] = max(f[i - 1][j], f[i - 1][j - v[i][k]] + w[i][k])
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m;
int v[N][N], w[N][N],s[N];
int f[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
cin >> s[i];
for (int j = 0; 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 = 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] << endl;
}
彻底一维
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m;
int v[N], w[N],s;
int f[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
cin >> s;
for (int j = 0; j < s; j ++ ) cin >> v[j] >> w[j];
for (int j = m; j >= 0; j -- )
for (int k = 0; k < s; k ++ )
if (j >= v[k]) f[j] = max(f[j], f[j - v[k]] + w[k]);
}
cout << f[m] << endl;
}