PAT1 1070 Mooncake

本文介绍了一种算法,用于解决在给定市场需求下,如何通过销售不同种类和价格的月饼来获得最大收益的问题。通过计算每种月饼的单价,并优先销售单价较高的月饼,实现了收益最大化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接
我的github

题目大意

给一些不同种类的月饼的数量和总价格,市场需求量是 D D D,求卖出月饼所能得到的最大收益

输入

每组包含一个测试用例

  • 用例第一行是两个正整数 N ≤ 1000 N\le1000 N1000表示月饼的种类数量, D ≤ 500 D\le500 D500表示市场需求量
  • 第二行有 N N N个正数,表示 N N N种月饼的数量
  • 第三行有 N N N个正数,表示 N N N种月饼的总价格

输出

对每个样例输出卖得的最大收益

样例输入

3 200
180 150 100
7.5 7.2 4.5

样例输出

9.45

解析

要卖出的收益最大,就先求出每种月饼的单价,然后依次从最贵的开始卖即可

我写的python有个测试点出现非0返回
然后又参考了dalao:传送门

我的python:

# -*- coding: utf-8 -*- 
# @Time : 2019/6/28 14:36 
# @Author : ValarMorghulis 
# @File : 1070.py
import functools


class moonCake:
    def __init__(self, amounts, tot):
        self.amounts = amounts
        self.tot = tot
        self.price = tot / amounts


def cmp(a, b):
    return -1 if a.price < b.price else 1


def solve():
    n, d = map(int, input().split())
    a = list(map(int, input().split()))
    b = list(map(float, input().split()))
    cake = list()
    for i in range(n):
        cake.append(moonCake(a[i], b[i]))
    cake = sorted(cake, key=functools.cmp_to_key(cmp), reverse=True)
    ans = 0
    for i in range(n):
        if cake[i].amounts < d:
            ans += cake[i].tot
            d -= cake[i].amounts
        else:
            ans = ans + cake[i].price * d
            break
    print("%.2f" % ans)


if __name__ == "__main__":
    solve()

dalao的python:

if __name__ == "__main__":
    line = input().split(" ")
    n, total = int(line[0]),int(line[1])
    line = input().split(" ")
    support = [float(x) for x in line]
    line = input().split(" ")
    price = [float(x) for x in line]
    per = []
    for x in range(n):
        if support[x] != 0 and price[x] != 0:
            unit = [price[x]/support[x], support[x], price[x]]
            per.append(unit)
    per = sorted(per, key = lambda x : -x[0])
    money = 0
    while(total > 0 and len(per) > 0):
        unit = per.pop(0)
        if total >= unit[1]:
            money += unit[2]
            total -= unit[1]
        else:
            money += total * unit[0]
            total = 0
    print('{:.2f}'.format(money))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值