洛谷 P1757(简单分组背包)

题目背景

直达通天路·小A历险记第二篇

题目描述

自01背包问世之后,小A对此深感兴趣。一天,小A去远游,却发现他的背包不同于01背包,他的物品大致可分为k组,每组中的物品相互冲突,现在,他想知道最大的利用价值是多少。

输入格式

两个数m,n,表示一共有n件物品,总重量为m

接下来n行,每行3个数ai,bi,ci,表示物品的重量,利用价值,所属组数

输出格式

一个数,最大的利用价值

输入输出样例

输入 #1复制
45 3
10 10 1
10 5 1
50 400 2
输出 #1复制
10

说明/提示

1<=m<=1000 1<=n<=1000 组数t<=100

 

对于 01 背包,假设每一个物品都属于一组。而分组背包就是  的一组物品 就相当于 01 背包的一个物品, 所以 分组背包 可以很简单的用 01 背包理解。

那么分组背包的顺序:

for (整个组)

    逆序for(容量)

          for(组内所有物品)

(丑陋的)Code:

#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define fi first
#define se second
#define CLR(a) while(!(a).empty()) a.pop()

using namespace std;
inline LL read() {
    LL s = 0,w = 1;
    char ch = getchar();
    while(!isdigit(ch)) {
        if(ch == '-') w = -1;
        ch = getchar();
    }
    while(isdigit(ch))
        s = s * 10 + ch - '0',ch = getchar();
    return s * w;
}
inline void write(LL x) {
    if(x < 0)
        putchar('-'), x = -x;
    if(x > 9)
        write(x / 10);
    putchar(x % 10 + '0');
}

const int maxn = 110;
vector<int> a[maxn],b[maxn];
/// a 重量, b 价值
set<int> t;
int dp[maxn * 10];

int main() {
//#ifndef ONLINE_JUDGE
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
//#endif
    int m = read(),n = read();
    rep(i,0,maxn){
        a[i].reserve(1100);
        b[i].reserve(1100);
    }
    for(int i = 1;i <= n;++ i){
        int x = read(),y = read(),z = read();
        t.insert(z);
        a[z].pb(x); b[z].pb(y);
    }
    for(auto it : t)
        for(int j = m;j >= 0;-- j)
            for(int k = 0;k < a[it].size();++ k)
                if(j >= a[it][k])
                    dp[j] = max(dp[j],dp[j - a[it][k]] + b[it][k]);
    write(dp[m]);
    return 0;
}

 

 

转载于:https://www.cnblogs.com/rookie-acmer/p/11342827.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值