多重背包

本文介绍了一个多重背包问题的实例,详细解析了如何通过动态规划算法求解最大价值的背包组合,给出了具体的C++代码实现,并解释了状态转移方程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
Time Limit: 1sec    Memory Limit:256MB
Description
Ouyang has 6 kinds of coins.
The number of the i-th coin is N[i] (0<=i<6).
Their value and weight are as follewed:
0. $0.01, 3g
1. $0.05, 5g
2. $0.10, 2g
3. $0.25, 6g
4. $0.50, 11g
5. $1, 8g
Ouyang want to run away from home with his coins.
But he is so weak that he can only carray M gram of coins.
Given the number of each coin he has, what is the maximal value of coins he can take?
 
Input
There are multiple cases.
Each case has one line with 7 integers: M (1<=M<=10000), A[i], (0<=i<6, 0<=A[i]<=100000).
 
Output

 The maximal value of coins he can take.

Sample Input
Copy sample input to clipboard
1 1 1 1 1 1 1
38 3  1  10  4  2  1
75 8  5  23  4  2  4
Sample Output
$0.00
$2.40
$6.10


#include <iostream>
#include <cstring>
#include <iomanip>
#include <algorithm> 

using namespace std;

double value[10]={0,0.01,0.05,0.10,0.25,0.50,1.00};
int weight[10]={0,3,5,2,6,11,8};
int num[10];
double res[10][100005];
int main()
{
    int gram;
    while(cin >> gram){
        int ncount=0;
        for(int i=1; i <= 6; ++i){
            cin >> num[i];
        }
        for(int i=0; i <= 6; i++) res[i][0]=0;
        for(int i=0; i <= gram; i++) res[0][i]=0; 
        
        for(int i=1; i <= 6; ++i){
            for(int w=0; w <= gram; ++w){
                res[i][w]=0;
                ncount=min(num[i],w/weight[i]);
                for(int j=0; j <= ncount; ++j){
                    res[i][w]=max(res[i][w],res[i-1][w-j*weight[i]]+j*1.0*value[i]);
                }
            }
        }
        cout << "$" << fixed << setprecision(2) << res[6][gram] << endl;
    }
}            

多重背包就是说每个物品的件数不一定,所以只要在原先的基础加多一层for循环,判断放入一件,两件。。。。等等时的情况就好,不过状态转移方程要变成

res[i][w]=max(res[i][w],res[i-1][w-j*weight[i]]+j*1.0*value[i]) 这里比较的不是res[i-1][w],而是res[i][w],也就是跟不放进当前这件比较


另外自己也看了下面一维解决背包,主要就是第二层的for要逆序



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值