![](https://img-blog.csdnimg.cn/20190316152233424.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2R5eWF5NTIx,size_16,color_FFFFFF,t_70)
这是胡凡算法中讲贪心时举的第一个例子;
![](https://img-blog.csdnimg.cn/20190316152332956.png)
而对于这道题而言,精髓就在与“单价”,只需要按照最高的单价去选择,之后需要考虑的就是需求量和供应量的关系,本题就解决了。
以下是完整代码:
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
struct mooncake{
double store; //库存量
double sell; //总售价
double price; //单价
}cake[1010];
bool cmp(mooncake a,mooncake b)
{
return a.price>b.price;
}
int main()
{
int n;
double D;
cin>>n>>D;
for(int i=0;i<n;i++)
{
cin>>cake[i].store;
}
for(int i=0;i<n;i++)
{
cin>>cake[i].sell;
cake[i].price=cake[i].sell / cake[i].store; //计算单价;
}
sort(cake,cake+n,cmp);
double ans=0; //收益
for(int i=0;i<n;i++){
if(cake[i].store <= D){
D=D-cake[i].store;
ans=ans+cake[i].sell; }
else{
ans+=cake[i].price*D;
break;
}
}
printf("%.2f\n",ans);
return 0;
}