1070 Mooncake (25 分)贪心算法

题目

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

解题思路

  题目大意: 给你N个月饼的货物重量还有价格,以及需求量,求怎样才能卖出最高的利润。
  解题思路: 直接算处每种月饼的单价,从高到低开始卖,卖完为止,累计计算每种月饼的花费。注意,考虑供不应求的情况,即需求了D大于N种月饼的累计量,直接输出所有的花费即可。

/*
** @Brief:No.1070 of PAT advanced level.
** @Author:Jason.Lee
** @Date:2019-01-08
** @Solution: Accepted!
*/
#include
#include
#include
using namespace std;

struct cake{
	float weight;
	float prices;
	float ppu;
};

int main(){
	int N,D;
	while(cin>>N>>D){
		vector<cake> vc(N);
		for(int i=0;i<N;i++){
			cin>>vc[i].weight;
		}
		for(int i=0;i<N;i++){
			cin>>vc[i].prices;
			vc[i].ppu = vc[i].prices/vc[i].weight;
			//cout<<"i = "<}
		sort(vc.begin(),vc.end(),[](cake a,cake b){return a.ppu>b.ppu;});
		int index = 0;
		float coast = 0.0f,request = D;
		while(request>0&&index<N){
			if(request>=vc[index].weight){
				coast+=vc[index].prices;
				request-=vc[index].weight;
			}else{
				coast+=request*vc[index].ppu;
				request = 0;
			}
			//cout<<"request= "<++;
		}
		printf("%.2f\n",coast);
	}
	return 0;
}

1070 Mooncake (25 分)贪心算法_第1张图片

总结

  最简单的贪心策略,没什么难的,PAT乙级1020的改编版。第三个测试点D会小于所有的月饼数量之和,注意即可。

你可能感兴趣的:(PAT-Advanced,Level)