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

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

代码

#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++;
    		}

结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhanggirlzhangboy/article/details/82934797
今日推荐