[PTA] moon cake

Title repeat

Chinese people eat moon cake is in the Mid-Autumn Festival a traditional food, different regions have many different flavors of moon cake. Now given all kinds of moon cake inventory, total price, and the maximum demand of the market, you can get the maximum benefit calculated how much.

Note: Allow removing a portion of the stock sale. Case examples given is this: If we have three kinds of moon cake, its stocks were 18,15,10 tons, the total price respectively 75,72,45 billion. If the maximum market demand is only 20 million tons, then we should be the maximum revenue strategy to sell all of the 150,000 tons of the two kinds of moon cake, as well as 50,000 tons of the three kinds of moon cake, get 72 + 45/2 = 94.5 (million) .

Input formats:

Each input comprises a test. Each test case is given to a positive integer not more than 1000 N represents the number of types of moon cake, and no more than 500 (in units of thousands of tons) of the positive integer D represents the maximum demand of market. Then given N th row represents a positive number of stocks of each moon cake (in units of thousands of tons); N last line gives positive number indicates a total sales price of each moon cake (in units of billions). Between numbers separated by a space.

Output formats:

For each test, the maximum benefit in the output line, in units of billions and accurately to two decimal places.

Sample input:

3 20
18 15 10
75 72 45    

Sample output:

94.50

answer

Feeling is a knapsack problem, rather than the 0-1 knapsack problem, the article knapsack problem is divisible, so it can be greedy algorithm, greedy to the highest price, using the sort of structure can be sorted.

100 ++ AND

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct node{
    double num;
    double sumPrice;
    double singlePrice;
};
bool cmp(node n1,node n2)
{
    return n1.singlePrice>n2.singlePrice;
}
int main()
{
    int n;
    double sum;
    node nds[1005];

    cin>>n>>sum;

    for(int i=0;i<n;i++)
    {
        cin>>nds[i].num;
    }
    for(int i=0;i<n;i++)
    {
        cin>>nds[i].sumPrice;
        nds[i].singlePrice=nds[i].sumPrice/nds[i].num;
    }
    sort(nds,nds+n,cmp);
    double money=0;
    int i=0;
    while(sum>0&&i<n)
    {
        if(sum>nds[i].num)
        {
            sum-=nds[i].num;

            money+=nds[i].sumPrice;
            i++;
        }
        else
        {
           break;
        }

    }
    money+=sum*nds[i].singlePrice;
    printf("%.2f",money);
    return 0;
}

Published 200 original articles · won praise 99 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_43889841/article/details/104074987