思路

  • 根据月饼的总价和数量计算出每一种月饼的单价
  • 用结构体存储月饼的数量,总价,单价;用结构体数组存储月饼结构体
  • 将月饼数组按照单价从大到小排序
  • 根据需求量need的大小,从单价最大的月饼开始售卖
  • 将销售掉这种月饼的价格累加到result中,最后输出result
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct mooncake{
    float mount, price, unit;
};
int cmp(mooncake a, mooncake b) {
    return a.unit > b.unit;
}
int main() {
    int n, need;
    cin >> n >> need;
    vector<mooncake> a(n);
    for (int i = 0; i < n; i++) scanf("%f", &a[i].mount);
    for (int i = 0; i < n; i++) scanf("%f", &a[i].price);
    for (int i = 0; i < n; i++) a[i].unit = a[i].price / a[i].mount;
    sort(a.begin(), a.end(), cmp);
    float result = 0.0;
    for (int i = 0; i < n; i++) {
        if (a[i].mount <= need) {
            result = result + a[i].price;
        } else {
            result = result + a[i].unit * need;
            break;
        }
        need = need - a[i].mount;
    }
    printf("%.2f",result);
    return 0;
}

参考

https://www.liuchuo.net/archives/543