PAT Grade B 1020 Mooncake (25 points)

topic content

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

Note: Part of the stock is allowed to be withdrawn at the time of sale. The situation given in the example is as follows: if we have 3 kinds of moon cakes, the inventory is 180,000 tons, 150,000 tons, and the total selling price is 7.5 billion, 7.2 billion, and 4.5 billion yuan. If the maximum demand in the market is only 200,000 tons, then our maximum profit strategy should be to sell all 150,000 tons of the second type of moon cakes and 50,000 tons of the third type of moon cakes to obtain 72 + 45/2 = 9.45 billion (billion yuan) .

Input format:

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

Output format:

For each group of test cases, output the maximum profit in one line, in billions of yuan and accurate to 2 decimal places.

Input sample:

3 20
18 15 10
75 72 45

no blank line at the end

Sample output:

94.50

no blank line at the end

Problem solving ideas

Use the structure array to access the inventory of moon cakes, total selling price, unit price, unit price = total selling price/inventory quantity , and the biggest profit in the question is very simple. , so you need to sort the structures in the order of unit price from high to low, and after accumulating the total revenue, printf formatted output!

Detailed code

#include <iostream>
#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;
    double D;
    cin>>n>>D;
    for(int i = 0;i < n;i++){
        cin>>cake[i].store;
    }
    for(int i = 0;i < n;i++){
        cin>>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;
            ans += cake[i].sell;
        }else{
            ans+=cake[i].price * D;
            break;
        }
    }
    printf("%.2f\n",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45660485/article/details/119299136