题目大意:有N种月饼,给出每种月饼的库存量和总价,现在需要重量D的月饼,输出可能获得的最大收入。
显然是依次选择单价最高的月饼,直到总重量达到D为止。但这题的坑点在于D和库存量和总价都需要设置成double型才能过。
AC代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
struct mooncake
{
double storage;
double price;
double profit;
bool operator < (const mooncake &other)
{
return this->profit > other.profit;
}
};
int main()
{
int N;
double D;
scanf("%d%lf", &N, &D);
vector<mooncake> v(N);
for (int i = 0; i < N; ++i)
scanf("%lf", &v[i].storage);
for (int i = 0; i < N; ++i)
{
scanf("%lf", &v[i].price);
v[i].profit = v[i].price / v[i].storage;
}
sort(v.begin(), v.end());
double sum = 0;
for (int i = 0; i < N; ++i)
{
if(v[i].storage <= D)
{
sum += v[i].price;
D -= v[i].storage;
}
else
{
sum += v[i].profit * D;
D = 0;
break;
}
}
printf("%.2f", sum);
return 0;
}