PAT-乙-1020 1020 月饼 (25 分)

本文介绍了一种通过算法实现月饼销售利润最大化的解决方案。通过定义月饼结构体并使用C++进行编码,算法首先计算每种月饼的单价,然后根据用户需求量与库存量对比,按单价从高到低排序销售,确保在满足需求的同时获得最高利润。

在这里插入图片描述
在这里插入图片描述

代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct {
	double num;
	double sumPrice;
	double singlePrice;
} Mooncake;

bool comparison(Mooncake a, Mooncake b) {
	return a.singlePrice>b.singlePrice;
}

int main() {
	
	double N;
	double buy;
	scanf("%lf", &N);
	scanf("%lf", &buy);

	vector<Mooncake> array(N);
	double maxCount = 0.0;
	double maxProfit = 0.0;

	for(int i=0; i<N; i++) {
		scanf("%lf", &array[i].num);
	}
	for(int i=0; i<N; i++) {
		scanf("%lf", &array[i].sumPrice);
	}
	for(int i=0; i<N; i++) {
		maxCount += array[i].num;
		maxProfit += array[i].sumPrice;
		array[i].singlePrice = array[i].sumPrice/array[i].num;
	}

	if(buy>maxCount) {
		printf("%.2f\n", maxProfit);
	} else {
		sort(array.begin(), array.end(), comparison);
		int start = 0;
		double profit = 0.0;
		//key point
		while(buy>1e-5) {
			if(array[start].num>buy) {
				profit += array[start].sumPrice * (buy/array[start].num);
				buy = 0;
			} else {
				profit += array[start].sumPrice;
				buy -= array[start].num;
			}
			start++;
		}
		printf("%.2f\n", profit);
	}

	return 0;
}

注解

1、结构体排序
2、当最大需求量比库存还多时,就不需要那么麻烦了,直接计算所有产品的总收益即可。否则,按单价由高到低卖,直到达到需求为止。当某种产品库存量小于当前需求,就全部卖出。否则,只需卖出到达到需求的量为止。
需要注意,用实型变量,在比较时不要用等号。
下面这部分是此题的核心代码

while(buy>1e-5) {
    			if(array[start].num>buy) {
    				profit += array[start].sumPrice * (buy/array[start].num);
    				buy = 0;
    			} else {
    				profit += array[start].sumPrice;
    				buy -= array[start].num;
    			}
    			start++;
    		}

结果

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值