背包问题(后续)

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值