博客
关于我
sdut 懒虫小鑫(快排里面,再加一个排序)
阅读量:780 次
发布时间:2019-03-25

本文共 582 字,大约阅读时间需要 1 分钟。

小鑫有n块矿石,每块矿石有两个属性:重量w和价值p。他每天能卖m块矿石,每次都会选重量最小的,如果多个重量相同则选价值高的。我们的目标是计算他能卖出m块矿石后所能得到的总价值。

首先,我们对所有矿石按照重量从小到大排序,同重量时按价值从高到低排序。这样排列后,前m个矿石的价值总和就是最大化的。这是因为在保证每天卖的都是重量最轻的前提下,这样能在总重量最小的前提下获得最大的价值。

具体步骤:

  • 将所有矿石按重量从小到大排序,当重量相同时,按价值从高到低排序。
  • 取前m个矿石,计算它们的价值总和。
  • 这样可以确保总价值最大化。对于输入的矿石,进行上述排序后,计算总和即可。

    现在,来看具体实现。首先,对输入的矿石进行排序,然后取前m个,计算它们的价值之和。

    代码示例如下:

    n, m = map(int, input().split())stones = []for _ in range(n):    w, p = map(int, input().split())    stones.append((w, p))# 按重量升序,价值降序排序stones.sort(key=lambda x: (x[0], -x[1]))total = sum(p for w, p in stones[:m])print(total)

    这样,我们就能得到小鑫总能赚到的最多钱数。

    转载地址:http://bjbuk.baihongyu.com/

    你可能感兴趣的文章
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>