题目如下:
这是一道简单贪心,保证眼前的利益,确保每次拿到的都是你目前能拿到的最大的利益,那这道题就解出来了。
为了确保能拿到最大利益,你需要每次尽量拿性价比最高,最划算的月饼。这里性价比最高就是单位价值最高。所以需要对单位价值进行排序,排序后对遍历月饼,每次先拿走单位价值最大的月饼,拿完这种月饼后再拿剩下月饼中单位价值最大的,直到拿的月饼到达需求量。
代码:
//请你计算可以获得的最大收益是多少
//贪心
//选择月饼单位价格最高的月饼进行排序,然后从高到低选
//foreverking
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
struct cake{
double num,sale;//num:总库存 sale:总售价 price: 单位价格
}mooncake[1000];//最多1K
int n,d;//n:月饼总量 d:最大需求量
int cnt;
double sum;
bool cmp(struct cake one,struct cake two){
double price_one = one.sale / one.num;
double price_two = two.sale / two.num;
return price_one > price_two;//按照降序
}
int main(){
cin >> n >> d;
for(int i = 0; i < n; i++) cin >> mooncake[i].num;//输入库存
for(int i = 0; i < n; i++) cin >> mooncake[i].sale;//输入总价
sort(mooncake,mooncake + n,cmp);//对月饼排序(单价),降序
//开始往最大需求里塞东西
for(int i = 0; i < n; i++){
if(d > cnt){
if(d - cnt > mooncake[i].num){//需求还可以完全吃下这一种月饼
sum += mooncake[i].sale;
cnt += mooncake[i].num;
}
else{//吃不完这一批货,那么按单价来,且这时候已经到达最大需求,break
sum += (mooncake[i].sale / mooncake[i].num) * (d - cnt);
break;
}
}
}
printf("%.2lf",sum);
return 0;
}
可以变得更简便一点,不用变量cnt记录拿了多少月饼,而是直接对需求D减。
//请你计算可以获得的最大收益是多少
//贪心
//选择月饼单位价格最高的月饼进行排序,然后从高到低选
//foreverking
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
struct cake{
double num,sale;//num:总库存 sale:总售价 price: 单位价格
}mooncake[1000];//最多1K
int n,d;//n:月饼总量 d:最大需求量
double sum;
bool cmp(struct cake one,struct cake two){
double price_one = one.sale / one.num;
double price_two = two.sale / two.num;
return price_one > price_two;//按照降序
}
int main(){
cin >> n >> d;
for(int i = 0; i < n; i++) cin >> mooncake[i].num;//输入库存
for(int i = 0; i < n; i++) cin >> mooncake[i].sale;//输入总价
sort(mooncake,mooncake + n,cmp);//对月饼排序(单价),降序
//开始往最大需求里塞东西
for(int i = 0; i < n; i++){
if(d > mooncake[i].num){//全部放下
sum += mooncake[i].sale;
d -= mooncake[i].num;
}
else{
sum += (mooncake[i].sale / mooncake[i].num) * d;
break;
}
}
printf("%.2lf",sum);
return 0;
}