题目
月饼是中国人在中秋佳节时吃的一种传统食品,不同地区有许多不同风味的月饼。现给定所有种类月饼的库存量、总售价、以及市场的最大需求量,请你计算可以获得的最大收益是多少。
注意:销售时允许取出一部分库存。样例给出的情形是这样的:假如我们有 3 种月饼,其库存量分别为 18、15、10 万吨,总售价分别为 75、72、45 亿元。如果市场的最大需求量只有 20 万吨,那么我们最大收益策略应该是卖出全部 15 万吨第 2 种月饼、以及 5 万吨第 3 种月饼,获得 72 + 45/2 = 94.5(亿元)。
输入格式:
每个输入包含一个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N 表示月饼的种类数、以及不超过 500(以万吨为单位)的正整数 D 表示市场最大需求量。随后一行给出 N 个正数表示每种月饼的库存量(以万吨为单位);最后一行给出 N 个正数表示每种月饼的总售价(以亿元为单位)。数字间以空格分隔。
输出格式:
对每组测试用例,在一行中输出最大收益,以亿元为单位并精确到小数点后 2 位。
输入样例:
3 20
18 15 10
75 72 45
输出样例:
94.50
代码长度限制
16 KB
时间限制
150 ms
内存限制
64 MB
错误思路:
我一开始考虑的是动态规划问题,所以直接使用递归去解决,下面是利用递归的代码,其实存在"非零返回"的问题。
正确思路:
题目中是取得最大收益,而且有了总量和总价,根据此求出每种月饼的单价,根据单价的高低选取月饼的数量,直到满足市场需求即可。
moon_type,moon_meet=list(map(int,input().split(' ')))
moon_save=list(map(float,input().split(' ')))
moon_price=list(map(float,input().split(' ')))
moon_unit_price=[] #每种月饼每吨销量的收益
for i in range(0,int(moon_type)):
moon_unit_price.append(moon_price[i]/moon_save[i])
global profit
profit=0
def moon_profile(moon_save,weight,i,meet,moon_state):
if i==len(moon_save): #当对每种月饼都进行了选择时
for index, i, j in zip(range(0, len(weight)), weight, moon_save): #对遍月饼的每种出售量是否全部遍历进行标记
if i == j: #
moon_state[index] = 1
weight.pop()
for i in range(0,len(moon_state)): #当这种月饼与之后面的月饼出售量都进行了排列组合之后,将其出栈
if moon_state[i]==1 and sum(moon_state[i:]) == len(moon_state[i:]):
weight.pop()
moon_state[i]=0
else:
for type_i_weight in range(0,int(moon_save[i])+1):
weight.append(type_i_weight)
if sum(weight) <= meet: #判断所选择月饼重量的策略是否超过市场序曲
all_price = 0
for i in range(0, len(weight)):
all_price = all_price + weight[i] * moon_unit_price[i]
global profile #利用全局变量储存最优利益
if all_price > profit:
profit = all_price
if(weight==moon_save): #当所选择的月饼策略皆为各种月饼的最大库存值时,结束递归遍历
print("%.2f"%profit)
break
moon_profile(moon_save, weight, i+1, meet,moon_state)
weight=[]
moon_state=[0]*len(moon_save) #记录每种月饼是否与其后面的月饼都进行了组合
moon_profile(moon_save, weight, i=0,meet=moon_meet,moon_state=moon_state)
正确代码链接:
添加链接描述