L2-003 月饼

本文介绍了一个通过算法来计算购买不同规格月饼时如何达到最经济实惠的方法。算法首先读取输入的月饼数量、每种月饼的重量和价格,然后计算出每种月饼的价格单位,并按单位价格从高到低进行排序。最后,算法根据需求重量计算出总花费。

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

#include <iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
struct mooncake{
   float mount;
   float price;
   float unit;
};
int cmp(mooncake a,mooncake b){
       return a.unit>b.unit;
 }
int main()
{
    int n;
   scanf("%d",&n);
    int need;
    scanf("%d",&need);
    mooncake *a=new mooncake [n];
    for(int i=0;i<n;i++){
        scanf("%f",&a[i].mount);
    }
    for(int i=0;i<n;i++){
        scanf("%f",&a[i].price);
    }
    for(int i=0;i<n;i++){
        a[i].unit=a[i].price/a[i].mount;
    }
    sort(a,a+n,cmp);
    float result =0.0;
    for(int i=0;i<n;i++){
        if(a[i].mount<=need){
            result=result+a[i].price;
        }else{
            result=result+a[i].unit*need;
            break;
        }
        need=need-a[i].mount;
    }
    printf("%.2f",result);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值