多重背包问题的二维优化
输入样例
4 5
1 2 3
2 4 1
3 4 3
4 5 2
输出样例:
10
朴素做法:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int M = 110;
int v[M],w[M],s[M],f[M][M];
int N,V;
int main()
{
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 ++ )
f[i][j] = max(f[i][j],f[i-1][j-k*v[i]]+k*w[i]);
cout << f[N][V];
return 0;
}
二维优化
将同类的物品分为若干堆,每一对看成新创造的新物品,之后按照01背包的思路即可
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 12010, M = 2010;
int v[N],w[N],f[M];
int main()
{
int n,m;
int a,b,s;
int cnt = 0;
cin >> n >> m;
for (int i = 0; i < n; i ++ )
{
int k=1;
cin >> a >> b >> s;
while(k <= s){
cnt++;
v[cnt] = k*a;
w[cnt] = k*b;
s -= k;
k *= 2;
}
if(s > 0){
cnt++;
v[cnt] = s*a;
w[cnt] = s*b;
}
}
for (int i = 1; i <= cnt; i ++ )
for (int j = m; j >= v[i]; j -- )
f[j] = max(f[j], f[j-v[i]]+w[i]);
cout << f[m];
return 0;
}
本文来自博客园,作者:泥烟,CSDN同名, 转载请注明原文链接:https://www.cnblogs.com/Knight02/p/15799104.html