PAT (Basic Level) Practice 1020 月饼

题目:给定所有种类月饼的库存量、总售价、以及市场的最大需求量,请你计算可以获得的最大收益是多少。

输入格式:

第一行给出正整数N(<1000,月饼的种类数),正整数D(<500,市场最大需求量,以万吨为单位)。

第二行给出N个正数表示每种月饼的库存量。(以万吨为单位)

第三行给出N个正数表示每种月饼的总售价。(以亿元为单位)

输出格式:

在一行中输出最大收益,以亿元为单位并精确到小数点后 2 位。 

思路:优先出售单价最高的月饼。(总售价 / 库存量 = 单价)

代码:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct moonCake{
    double inventory; // 库存 -- 万吨
    double totalPrice; // 总价 -- 亿元
    double unitPrice; // 单价 -- 亿元
};
bool myCompare(struct moonCake a,struct moonCake b){
    return a.unitPrice >= b.unitPrice;
}
int main(){
    int n = 0; // 月饼的种类数 < 1000
    cin >> n;
    int D = 0; // 市场的最大需求量 < 500 万吨
    cin >> D;
    struct moonCake * arr = new struct moonCake[n]; // N种月饼
    for(int i = 0 ; i < n ; i ++)
        cin >> arr[i].inventory; // 输入库存
    for(int i = 0 ; i < n ; i ++)
        cin >> arr[i].totalPrice; // 输入总售价
    // 计算每种月饼的单价
    for(int i = 0 ; i < n ; i ++)
        arr[i].unitPrice = (double)arr[i].totalPrice / arr[i].inventory;
    // 按单价从大到小排序
    sort(arr,arr+n,myCompare);
    double sum = 0;
    // 优先将单价最高的卖出
    for(int i = 0 ; i < n ; i ++){
        if(D >= arr[i].inventory){
            // 全部卖出
            sum += arr[i].totalPrice;
            D -= arr[i].inventory;
            // cout << "卖出:" << arr[i].totalPrice << "重量" << arr[i].inventory << endl;
        }else{
            // 部分卖出
            sum += D * arr[i].unitPrice;
            D = 0;
            // cout << "部分卖出:" << arr[i].totalPrice << "重量" << arr[i].inventory << endl;
            break;
        }
    }
    delete [] arr;
    printf("%0.2f\n",sum); // 格式化输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值