PAT Grade B | 1020 Mooncake (25 points)

Mooncake is a traditional food that Chinese people eat during the Mid-Autumn Festival. There are many mooncakes with different flavors in different regions. Given the inventory of all types of moon cakes, the total selling price, and the maximum demand in the market, please calculate the maximum benefit that can be obtained.

Note: Part of the inventory is allowed to be taken out when selling. The situation given in the example is as follows: If we have 3 kinds of moon cakes, the stocks are 18, 15 and 100,000 tons respectively, and the total selling price is 75, 72, and 4.5 billion yuan respectively. If the market’s maximum demand is only 200,000 tons, then our maximum profit strategy should be to sell all 150,000 tons of the second moon cake and 50,000 tons of the third moon cake to obtain 72 + 45/2 = 9.45 (billion yuan) .

Input format:

Each input contains a test case. Each test case first gives a positive integer N not exceeding 1000 to indicate the number of mooncake types, and a positive integer D not exceeding 500 (in 10,000 tons) to indicate the maximum demand in the market. The next line gives N positive numbers to indicate the inventory of each type of moon cake (in 10,000 tons); the last line gives N positive numbers to indicate the total selling price of each type of moon cake (in 100 million yuan). The numbers are separated by spaces.

Output format:

For each set of test cases, output the maximum profit in one line, with 100 million yuan as the unit and accurate to 2 decimal places.

Input sample:

3 20
18 15 10
75 72 45

Sample output:

94.50

Idea: This question is a typical greedy problem. We might as well store the information of each mooncake in a structure. Then sort the structure array according to the unit price of each moon cake from largest to smallest . The moon cakes in the front must be used first. It should be noted that the maximum demand may be greater than the total amount of all moon cakes.

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

struct MoonCake{
    
    	//月饼信息
    double price;	//单价
    double total_price;	//总价
    double count;	//总量
}mc[1000];

bool cmp(MoonCake a,MoonCake b){
    
    	//排序
    return a.price>b.price;
}

int main()
{
    
    
    int n,m;	//种类和最大需求量
    double cnt_price=0;	//最大获益
    cin >>n>>m;
    for(int i=0;i<n;i++)
        scanf("%lf",&mc[i].count);
    for(int i=0;i<n;i++){
    
    
        scanf("%lf",&mc[i].total_price);
        mc[i].price=mc[i].total_price/mc[i].count;
    }
    sort(mc,mc+n,cmp);
    int i=0;
    while(m&&i<=n){
    
    
        if(mc[i].count<=m){
    
    	//该月饼可以卖完
            cnt_price+=mc[i].total_price;
            m-=mc[i].count;
        }
        else{
    
    	//该月饼只能卖一部分
            cnt_price+=m*mc[i].price;
            m=0;
        }
        i++;
    }
    printf("%.2lf\n",cnt_price);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44888152/article/details/108641249
Recommended