编程语言
首页 > 编程语言> > c/c++贪心算法求月饼利润

c/c++贪心算法求月饼利润

作者:互联网

输入:

第1行:输入几种月饼n,需求量D
第2行:输入n种月饼各自的存量
第3行:输入n种月饼的总售价

例如:
3 20
18 15 10
75 72 45

输出:

最大收益

例如:94.50

代码:

#include<cstdio>
#include<algorithm>
using namespace std;

struct mooncake {
	double store;
	double sell;
	double price;
}cake[1010];

bool cmp(mooncake a, mooncake b) {
	return a.price > b.price;
}

int main() {
	int n=0;
	scanf_s("%d", &n);
	double D=0.0;
	scanf_s("%lf", &D);
	for (int i = 0; i < n; i++) {
		scanf_s("%lf", &cake[i].store);
	}
	for (int i = 0; i < n; i++) {
		scanf_s("%lf", &cake[i].sell);
		cake[i].price = cake[i].sell / cake[i].store;
	}
	sort(cake, cake + n, cmp); // 价格从高到低
	double ans = 0; //收益
	for (int i = 0; i < n; i++) {
		if (cake[i].store <= D) {
			D -= cake[i].store; // 第i种月饼全部卖出
			ans += cake[i].sell;
		}
		else {
			ans += cake[i].price * D;
			break;
		}
	}
	printf("%.2f\n", ans);

	return 0;
}

标签:月饼,int,double,scanf,c++,cake,price,store,贪心
来源: https://blog.csdn.net/sdhdsf132452/article/details/118545606