PAT B 1020月饼
题目描述:
月饼是中国人在中秋佳节时吃的一种传统食品,不同地区有许多不同风味的月饼。现给定所有种类月饼的库存量、总售价以及市场的最大需求量,试计算可以获得的最大收益是多少。
注意:销售时允许取出一部分库存。样例给出的情形是这样的:假如有三种月饼,其库存量分别为18、15、10万吨,总售价分别为75、72、45亿元。如果市场的最大需求量只有20万吨,那么最大收益策略应该是卖出全部15万吨第二种月饼以及5万吨第三种月饼,获得72+45/2=94.5(亿元)多少。
#include<stdio.h>
#include<string.h>
#include<algorithm>
struct mooncake
{
double store; //月饼库存
double sell; //月饼总价
double price; //月饼单价
}cake[1001];
int cmp(const void* a, const void* b) {
int mark1 = ((struct mooncake*)a)->price;
int mark2 = ((struct mooncake*)b)->price;
return mark1 < mark2 ? 1 : -1;
}
int main()
{
int n; //月饼种类
double need; //需求量
printf("请输入:");
scanf("%d %lf", &n, &need);
for (int i = 0; i < n; i++)
{
printf("请输入库存:");
scanf("%lf",&(cake[i].store));
}
for (int i = 0; i < n; i++)
{
printf("请输入总价:");
scanf("%lf", &(cake[i].sell));
cake[i].price = (cake[i].sell) / (cake[i].store);
}
qsort(cake, n, sizeof(struct mooncake), cmp); //按价格从高到低排序
/*for (int i = 0; i < n; i++)
{
printf("%lf\n", cake[i].price);
}*/
double weight=0; //已卖量
double abs=0; //收益
for (int j = 0; weight<need; j++)
{
if (cake[j].store <= need - weight) //第i种库存不够剩余的需求量
{
weight += cake[j].store;
abs += cake[j].sell;
}
else //第i种库存够剩余的需求量,取最多的第i种
{
abs += (need - weight) * (cake[j].price);
weight = need;
}
}
printf("%lf", abs);
return 0;
}