题目:给定所有种类月饼的库存量、总售价、以及市场的最大需求量,请你计算可以获得的最大收益是多少。
输入格式:
第一行给出正整数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); // 格式化输出
}