分组背包

昨天牛客遇到一个多重背包问题,没想到二进制优化。于是补了一下题,发现了很多漏洞 当你在家里发现一只蟑螂的时候,其实已经有一万只蟑螂了 (蟑螂=漏铜

分组背包,在01背包的基础上加上了组别限制,同属于一组的物品只能选一次。
例题:洛谷 P1757

分组背包是01背包的变形,如何确保同组的物品只选一次呢?只需将遍历同组物品的循环放在遍历背包容量的循环之下,这样,当背包容量为i时,只由j组中的某个物品k更新得到最大值

细节看代码以及注释:

/*
 * @Author: hesorchen
 * @Date: 2020-04-14 10:33:26
 * @LastEditTime: 2020-06-21 12:00:13
 * @Link: https://hesorchen.github.io/
 */
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI cos(-1)
#define PB push_back
#define ll long long
#define INF 0x3f3f3f3f
#define mod 3123456777
#define pll pair<ll, ll>
#define lowbit(abcd) (abcd & (-abcd))
#define max(a, b) ((a > b) ? (a) : (b))
#define min(a, b) ((a < b) ? (a) : (b))

#define IOS                      \
    ios::sync_with_stdio(false); \
    cin.tie(0);                  \
    cout.tie(0);
#define FRE                              \
    {                                    \
        freopen("in.txt", "r", stdin);   \
        freopen("out.txt", "w", stdout); \
    }

inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9')
    {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9')
    {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}
//==============================================================================

vector<pll> vec[1010];
ll dp[1010];
ll k = 0;
int main()
{
    ll n, m;
    cin >> m >> n;
    for (int i = 1; i <= n; i++)
    {
        ll a, b, c;
        cin >> a >> b >> c;
        k = max(k, c); //更新组数
        vec[c].PB(make_pair(a, b));
    }
    // i、j、l分别表示 第i组、背包容量为l、组中的第j个物品
    for (int i = 1; i <= k; i++)
        for (int l = m; l >= 0; l--)
            for (int j = 0; j < vec[i].size(); j++) //将j循环放在l循环之下,可以确保前i组,背包容量为l时,最大价值只由第i组中的一个物品更新
                if (l >= vec[i][j].first)
                    dp[l] = max(dp[l], dp[l - vec[i][j].first] + vec[i][j].second);
    cout << dp[m] << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hesorchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值