PAT-BASIC1020——月饼/PAT-ADVANCED1070——Mooncake

我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC

我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED

原题链接:

PAT-BASIC1020:https://pintia.cn/problem-sets/994805260223102976/problems/994805301562163200

PAT-ADVANCED1070:https://pintia.cn/problem-sets/994805342720868352/problems/994805399578853376

题目描述:

PAT-BASIC1020:

PAT-ADVANCED1070:

知识点:贪心算法

思路:优先售卖单价最高的商品

很明显的贪心算法。

时间复杂度是O(nlogn),其中n为月饼种类数。空间复杂度为O(n)。

C++代码:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct product {
	double quantity;
	double price;
};

bool compare(product product1, product product2);

int main() {
	int type;
	int need;

	cin >> type >> need;

	double quantity;
	double price;

	vector<double> quantities;
	vector<double> prices;
	vector<product> products;

	product moonCake;

	for (int i = 0; i < type; i++) {
		cin >> quantity;
		quantities.push_back(quantity);
	}
	for (int i = 0; i < type; i++) {
		cin >> price;
		prices.push_back(price);
	}
	for (int i = 0; i < type; i++) {
		moonCake.quantity = quantities[i];
		moonCake.price = prices[i];
		products.push_back(moonCake);
	}
	sort(products.begin(), products.end(), compare);
	double total = 0;
	double profit = 0;
	for (int i = 0; i < products.size(); i++) {
		if (total + products[i].quantity <= need) {
			profit += products[i].price;
			total += products[i].quantity;
		} else {
			profit += (need - total) * products[i].price / products[i].quantity;
			break;
		}
	}
	printf("%.2f", profit);
}

bool compare(product product1, product product2) {
	if (product1.price / product1.quantity - product2.price / product2.quantity >= 0) {
		return true;
	} else {
		return false;
	}
}

C++解题报告:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值