分组背包问题
作者:
烟雨宴江南
,
2024-07-24 23:33:50
,
所有人可见
,
阅读 1
//朴素解法
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int v[N][N], w[N][N], s[N]; //v为体积,w为价值,s代表第i组物品的个数
int dp[N][N]; //只从前i组物品中选,当前体积小于等于j的最大值
int main()
{
int n, V;
cin >> n >> V;
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 = 0; j <= V; j++)
{
dp[i][j] = dp[i - 1][j]; //不选
for(int k = 1; k <= s[i]; k++)
{
if(v[i][k] <= j) dp[i][j] = max(dp[i][j], dp[i - 1][j - v[i][k]] + w[i][k]);
}
}
}
cout << dp[n][V] << endl;
return 0;
}
//优化解法
#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(v[i][k] <= j) f[j] = max(f[j], f[j - v[i][k]] + w[i][k]);
}
}
}
cout << f[m] << endl;
return 0;
}