<OJ_Sicily>Coins完全背包问题

40 篇文章 0 订阅

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.

问题解释:这相当于是一个完全背包问题

输入:每一个case的输入都是1行,每一行包含7个数,第一个数为背包容量,后面6个数为相应的硬币数量

输出:在背包容量允许的情况下所获得的最大价值

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <memory.h>

using namespace std;
double v[6] = {0.01,0.05,0.10,0.25,0.50,1};  //各硬币的价值
int w[6] = {3,5,2,6,11,8};     //各硬币的重量
int A[6];
double totalV[7][10005];       

int main(int argc, const char * argv[]) {
    int M;
    while (cin >> M) {
        if (M <= 0) break;
        memset(totalV, 0, sizeof(totalV));
        for (int i = 0; i < 6; i ++) {
            cin >> A[i];
        }
        for (int i = 5; i >= 0 ; i--) {
            for (int j = 0; j <= M; j++) {
                totalV[i][j] = totalV[i+1][j];
                for (int k = 1; k <= A[i] ; k++) {   //寻找价值最优解
                    if (k * w[i] > j){               //加入第i个硬币后,重量超重放弃该硬币的加入        
                        break;   
                    }
                    else{  //第i个硬币加入后没有超重,则选择加入或者不加入的最优值
                        //totalV[i][j] = max(totalV[i+1][j],totalV[i][j]);
                        totalV[i][j] = max(totalV[i][j],totalV[i+1][j-k * w[i]]+k * v[i]);
                    }
                }
            }
        }
        cout << "$" << setprecision(2) << setiosflags(ios::fixed) << totalV[0][M] << endl;
    }
    return 0;
}                                 


后记:

在这里还是使用一个二维数组来获取最高价值。每一个问题的最优解都是建立在子问题的最优解的基础上的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值