pat-B1020-月饼

这篇博客介绍了如何解决B1020月饼问题,采用贪心算法,优先选择单价最高的月饼以获得最大利润。博主提醒注意在处理库存和总价时,由于double类型的精度问题,直接从int转换可能会导致计算错误。
摘要由CSDN通过智能技术生成

题目链接->link

思路

  1. 贪心的思路,只要选单价最高的月饼最多,那么总利润也是最高。
  2. 对月饼按照单价从小到大排序,如果月饼库存小于需求,那么库存全选上,需求减少相应数量;直到库存大于需求,那么最多选择当前剩余需求乘上单价。
  3. 坑点:如果库存和总价用int表示,然后计算单价时强制转为double,那么实际数会出错,因为double精度高于int。

代码

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

using namespace std;

const int maxn=1005;
struct mooncake{
    double reserve;//库存
    double totalPrice;//总价
    double singlePrice;//单价
}cake[maxn];

bool cmp(mooncake a,mooncake b){
    return a.singlePrice>b.singlePrice;
}

int main(){
    int n,need;
    cin>>n>>need;
    for(int i=0;i<n;i++){
        cin>>cake[i].reserve;//输入库存
    }
    for(int i=0;i<n;i++){
        cin>>cake[i].totalPrice;//输入总售价
    }
    for(int i=0;i<n;i++){
        cake[i].singlePrice=cake[i].totalPrice/cake[i].reserve;//计算单价
        //printf("%f ",cake[i].singlePrice);
    }
    sort(cake, cake+n, cmp);//将月饼按照单价从大到小排序
    double profit=0;
    if(need>0){//如果需求大于0则继续
        for(int i=0;i<n;i++){
            if(cake[i].reserve<=need){//如果库存小于等于需求,那么全加上,并减少对应需求
                profit+=cake[i].totalPrice;
                need-=cake[i].reserve;
            }
            else {
                profit+=need*cake[i].singlePrice;
                break;
            }
        }
        printf("%.2f\n",profit);
    }
    else cout<<0;//如果需求等于0,则直接输出0
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值