贪心算法的应用(PAT 1070 Mooncake)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alex1997222/article/details/86253146

贪心法是求解一类最优化问题的方法,它总是考虑局部情况下的最优解

比如在huffman树的构造中,利用贪心算法依次选取数组中权值最大的两个结点组合成新的结点,依次类推

该算法确定全局结果是最优的(每一次决策都是最优的决策)

比如下面这么一道题:

Mooncake is a Chinese bakery product traditionally eaten during the Mid-Autumn Festival. Many types of fillings and crusts can be found in traditional mooncakes according to the region's culture. Now given the inventory amounts and the prices of all kinds of the mooncakes, together with the maximum total demand of the market, you are supposed to tell the maximum profit that can be made.

Note: partial inventory storage can be taken. The sample shows the following situation: given three kinds of mooncakes with inventory amounts being 180, 150, and 100 thousand tons, and the prices being 7.5, 7.2, and 4.5 billion yuans. If the market demand can be at most 200 thousand tons, the best we can do is to sell 150 thousand tons of the second kind of mooncake, and 50 thousand tons of the third kind. Hence the total profit is 7.2 + 4.5/2 = 9.45 (billion yuans).

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers N (≤1000), the number of different kinds of mooncakes, and D (≤500 thousand tons), the maximum total demand of the market. Then the second line gives the positive inventory amounts (in thousand tons), and the third line gives the positive prices (in billion yuans) of N kinds of mooncakes. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the maximum profit (in billion yuans) in one line, accurate up to 2 decimal places.

Sample Input:

3 200
180 150 100
7.5 7.2 4.5

Sample Output:

9.45

现在月饼需求量为D,已知n种月饼的库存和总售价,问如何销售这些月饼,使收益能够最大

首先确定贪心策略:“总是选择单价最高的月饼销售,可以获得最大收益"

然后进行决策:

(1)如果当前单价最高的月饼库存量满足需求量,直接全部购买该种月饼即可

(2)  如果库存量无法满足需求量,将该月饼的库存全部买下,需求量减去该月饼库存量,然后进行下一步决策(即下一单价最高月饼能否满足)

编写代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;

struct moonCake
{
	double price;   //单价
	double store;   //总库存量
	double sell;    //总售价
}moonCakes[1010];

bool cmp(moonCake a, moonCake b) {  //将月饼根据单价排序
	return a.price > b.price;
}

int main() {
	int N;
	double M;  //N月饼种类,M需求量
	double amount = 0.0;  //总收益
	scanf("%d %lf", &N, &M);
	for (int i = 0; i < N; ++i) {
		scanf("%lf", &moonCakes[i].store);
	}
	for (int i = 0; i < N; ++i) {
		scanf("%lf", &moonCakes[i].sell);
		moonCakes[i].price = moonCakes[i].sell / moonCakes[i].store;
	}
	sort(moonCakes, moonCakes + N, cmp);  //将价格从高到低依次排序
	for (int i = 0; i < N; ++i) {
		if (moonCakes[i].store > M) {   //如果库存大于需求的话
			amount += moonCakes[i].price*M;
			break;
		}
		else {
			amount += moonCakes[i].sell;   //否则直接全拿下
			M -= moonCakes[i].store;
		}
	}
	
	printf("%.2f\n", amount);

	system("PAUSE");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/alex1997222/article/details/86253146
今日推荐