A1070 Mooncake (25 分)

本文介绍了一种通过计算月饼性价比并排序,以实现预算内最大化购买价值的算法。使用C++实现,通过输入月饼的存储量和价格,计算每个月饼的性价比,按性价比从高到低排序,然后在预算范围内选择性价比最高的月饼进行购买,直至预算用尽。

题目里面除了N和D为整数已知,其余的都不知道,不妨其他的都设为double。
小错误总结:这个题目里面,double的输入是%lf,输出是%f,第一遍直接都用了%f,导致了结果为0.00

#include<cstdio>
#include<algorithm>
using namespace std;
struct mooncake
{
	double storage;
	double price;
	double bizhi;//按照比值由大到小排序
}mc[1010];
bool cmp(mooncake a, mooncake b)
{
	return a.bizhi > b.bizhi;
}
int main()
{
	int n,d;
	scanf("%d %d", &n, &d);
	for (int i = 0; i < n; i++)
	{
		scanf("%lf", &mc[i].storage);
	}
	for (int i = 0; i < n; i++)
	{
		scanf("%lf", &mc[i].price);
		mc[i].bizhi = mc[i].price / mc[i].storage;
		
	}
	sort(mc, mc + n, cmp);
	double profit=0.0;
	for (int i = 0; i < n; i++)
	{
		if (mc[i].storage <= d)
		{
			profit += mc[i].price;
			d -= mc[i].storage;
		}
		else
		{
			profit += mc[i].price * d/mc[i].storage;
			break;
		}
	}
	printf("%.2f", profit);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值