L2-003 Mooncake (25 points) [PTA][greedy]

Moon cake is a traditional food that Chinese people eat during the Mid-Autumn Festival. There are many moon cakes 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 profit you can obtain.

Note: Part of the inventory is allowed to be taken out during sales. 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 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 moon cake and 50,000 tons of the third moon cake, and get 72 + 45/2 = 9.45 (billion yuan) .

Input format:

Each input contains a test case. Each test case first gives a positive integer not more than 1000 N to represent the number of mooncake types, and a positive integer not more than 500 (in 10,000 tons) to represent 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, in 100 million yuan and accurate to 2 decimal places.

Input sample:

3 20
18 15 10
75 72 45

Sample output:

94.50

 You must use double, otherwise one example won’t pass

ac code:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<set>
#include<queue>
#include<stack>
using namespace std;
const int maxv = 100100;
struct mooncake
{
    double price,num;
    double p_n;
}m[1100];
bool cmp(mooncake a,mooncake b)
{
    return a.p_n>b.p_n;
}
int main()
{
    int N,D;
    cin>>N>>D;
    for(int i=0;i<N;i++)
    {
        cin>>m[i].num;
    }
    for(int i=0;i<N;i++)
    {
        cin>>m[i].price;
        m[i].p_n=m[i].price/m[i].num;
    }
    sort(m,m+N,cmp);
    double ans=0;
    for(int i=0;i<N;i++)
    {
        if(m[i].num<D)
        {
            ans+=m[i].price;
            D-=m[i].num;
        }
        else
        {
            ans+=m[i].p_n*D;
            break;
        }
    }
    printf("%.2f",ans);
    return 0;
}


 

Guess you like

Origin blog.csdn.net/qq_43660826/article/details/110110871