多重背包问题
作者:
烟雨宴江南
,
2024-07-24 20:09:52
,
所有人可见
,
阅读 1
//朴素解法
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int dp[N][N], v[N], w[N], s[N];
int main()
{
int n, V;
cin >> n >> V;
for(int i = 1; i <= n; i++) cin >> v[i] >> w[i] >> s[i];
for(int i = 1; i <= n; i++)
{
for(int j = 0; j <= V; j++)
{
for(int k = 0; k <= s[i] && k * v[i] <= j; k++)
{
dp[i][j] = max(dp[i][j], dp[i - 1][j - k * v[i]] + k * w[i]);
}
}
}
cout << dp[n][V] << endl;
return 0;
}
//优化解法 (二进制拆分优化)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 25000, M = 2000;
int v[N], w[N], dp[N];
int main()
{
int n, V;
cin >> n >> V;
int cnt = 0;
for(int i = 1; i <= n; i++)
{
int a, b, s;
cin >> a >> b >> s;
int k = 1;
while(k <= s)
{
cnt++;
v[cnt] = a * k;
w[cnt] = b * k;
s = s - k;
k = k * 2;
}
if(s > 0)
{
cnt++;
v[cnt] = a * s;
w[cnt] = b * s;
}
}
n = cnt;
for(int i = 1; i <= n; i++)
{
for(int j = V; j >= v[i]; j--)
{
dp[j] = max(dp[j], dp[j - v[i]] + w[i]);
}
}
cout << dp[V] << endl;
return 0;
}