【题意】
给出一些月饼的总量和总价,按照重量需求选购月饼使得总价最高
【思路】
计算出重量和价钱的比例,从小到大排一下即可
【注意点】
虽然题中例子给的重量都是整数,但题干中并没明确说重量是整数,其实判题程序中有浮点数的情况。。。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef struct{
float amount;
float price;
float weight;
}mooncake;
bool cmp(mooncake m1, mooncake m2){
return m1.weight<m2.weight;
}
int main(int argc, char const *argv[])
{
vector<mooncake> mooncakes;
int n;
float d;
cin >> n >> d;
mooncakes.resize(n);
for(int i=0; i<n; i++){
cin >> mooncakes[i].amount;
}
for(int i=0; i<n; i++){
cin >> mooncakes[i].price;
mooncakes[i].weight = mooncakes[i].amount/mooncakes[i].price;
}
sort(mooncakes.begin(),mooncakes.end(),cmp);
float profit = 0.0;
int index = 0;
while(d && index<n){
float amount = min(mooncakes[index].amount,d);
d -= amount;
profit += amount/mooncakes[index].weight;
index++;
}
printf("%.2f", profit);
system("pause");
return 0;
}