1070 Mooncake (25 分)

本文探讨了一道经典的贪心算法题目,通过分析蛋糕购买问题的两种实现版本,揭示了算法设计与测试点的重要性。文章详细解释了如何通过计算单位价格来选择最优购买策略,并对比了PAT与牛客网的不同测试点,强调了数据类型和边界条件的考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题是我接触得最早得贪心算法题,但是没想到这次做还是有个测试点没过去。
主要是样例给得数据让我主观得认为,总量一定是整数。
然后我反复得读题目,似乎也没发现这里隐藏得陷阱。
出题人这样搞我们真的不怕下雨天被雷带走吗?

版本1

PAT测试点

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1e3+5;
struct cake{
	double price,per,amount;
}C[maxn];
bool cmp(cake a, cake b){
	return a.per > b.per;
}
int main(){
	int n;
	double m;
	scanf("%d%lf",&n,&m);
	for(int i=0;i<n;i++){
		scanf("%lf",&C[i].amount);
	}
	for(int i=0;i<n;i++){
		scanf("%lf",&C[i].price);
		C[i].per = C[i].price/C[i].amount;
	}
	sort(C,C+n,cmp);
	double ans=0.0;
	for(int i=0;i<n;i++){
		if(m > C[i].amount){
			ans += C[i].price;
			m -= C[i].amount;
		}else {
			ans += m * C[i].per;
			break;
		}
	}
	printf("%.2f\n",ans);
	return 0;
}

版本2

牛客网测试点

#include<bits/stdc++.h>
using namespace std;
struct cake{
	double amounts, price, single;
}E[1010];
bool cmp(cake a, cake b){
	return a.single > b.single;
}
int main(){
	int n;
	double d, t;
	cin >> n >> d;
	for(int i = 0; i < n; i++){
		cin >> t;
		E[i].amounts = t;
	}
	for(int i = 0; i < n; i++){
		cin >> t;
		E[i].price = t;
		E[i].single = t/E[i].amounts;
	}
	sort(E, E + n, cmp);
	double ans = 0;
	for(int i = 0; i < n; i++){
		if(d >= E[i].amounts){
			ans += E[i].price;
			d -= E[i].amounts;
		}else{
			ans += E[i].single * d;
			break;
		}
	}
	printf("%.2f\n", ans);
	return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值