题目链接->link
思路
- 贪心的思路,只要选单价最高的月饼最多,那么总利润也是最高。
- 对月饼按照单价从小到大排序,如果月饼库存小于需求,那么库存全选上,需求减少相应数量;直到库存大于需求,那么最多选择当前剩余需求乘上单价。
- 坑点:如果库存和总价用int表示,然后计算单价时强制转为double,那么实际数会出错,因为double精度高于int。
代码
#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
const int maxn=1005;
struct mooncake{
double reserve;//库存
double totalPrice;//总价
double singlePrice;//单价
}cake[maxn];
bool cmp(mooncake a,mooncake b){
return a.singlePrice>b.singlePrice;
}
int main(){
int n,need;
cin>>n>>need;
for(int i=0;i<n;i++){
cin>>cake[i].reserve;//输入库存
}
for(int i=0;i<n;i++){
cin>>cake[i].totalPrice;//输入总售价
}
for(int i=0;i<n;i++){
cake[i].singlePrice=cake[i].totalPrice/cake[i].reserve;//计算单价
//printf("%f ",cake[i].singlePrice);
}
sort(cake, cake+n, cmp);//将月饼按照单价从大到小排序
double profit=0;
if(need>0){//如果需求大于0则继续
for(int i=0;i<n;i++){
if(cake[i].reserve<=need){//如果库存小于等于需求,那么全加上,并减少对应需求
profit+=cake[i].totalPrice;
need-=cake[i].reserve;
}
else {
profit+=need*cake[i].singlePrice;
break;
}
}
printf("%.2f\n",profit);
}
else cout<<0;//如果需求等于0,则直接输出0
return 0;
}