1.混合背包问题
思路:将多重背包通过2进制优化------->01背包,将混合三类背包问题转化为两种(01背包+完全背包)
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m;
int f[N];
struct Thing
{
int kind, v, w;
};
vector<Thing> things;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < n; i++)
{
int v, w, s;
cin >> v >> w >> s;
if (s < 0)
things.push_back({-1, v, w});
else if (s == 0)
things.push_back({0, v, w});
else
{
for (int k = 1; k <= s; k *= 2)//将多重背包通过2进制优化------->01背包
{
s -= k;
things.push_back({-1, v * k, w * k});
}
if (s > 0)
things.push_back({-1, v * s, w * s});
}
}
for (auto thing : things)
{
if (thing.kind < 0)
{
for (int j = m; j >= thing.v; j--)
f[j] = max(f[j], f[j - thing.v] + thing.w);
}
else
{
for (int j = thing.v; j <= m; j++)
f[j] = max(f[j], f[j - thing.v] + thing.w);
}
}
cout << f[m] << endl;
return 0;
}
2.二维费用的背包问题
思路:将01背包问题增加一维(重量)
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n,v,m;
int f[N][N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> v >> m;
for (int i = 0; i < n;i++)
{
int a, b, c;
cin >> a >> b >> c;
for (int j = v; j >= a;j--)
for (int k = m; k >= b;k--)
f[j][k] = max(f[j][k], f[j - a][k - b] + c);
}
cout << f[v][m] << endl;
return 0;
}