按性价比排完先拿谁

👁️ 2 人浏览 💬 0 人评论 ❤️ 添加收藏

三件物品(重量, 价值)是 (6,30)(4,24)(5,20),按每单位重量的价值从高到低排(交叉相乘比较,避开小数)。

运行下面这段程序:

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Item {
    int w, v;
};

int main() {
    vector<Item> items = {{6, 30}, {4, 24}, {5, 20}};
    stable_sort(items.begin(), items.end(), [](const Item& a, const Item& b) { return a.v * b.w > b.v * a.w; });
    for (size_t i = 0; i < items.size(); i++) cout << (i ? "/" : "") << items[i].w;
    cout << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论
🔒 登录并作答后可看讨论