贪心算法-算法笔记PAT_B1020

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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值