-
(0201)-(救生艇)
第
i个人的体重为people[i],每艘船可以承载的最大重量为limit。每艘船最多可同时载两人,但条件是这些人的重量之和最多为
limit。返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
注意:1≤people.length≤50000,1≤people[i]≤limit≤30000
题目来源:领扣LintCode—1061救生艇
解题思路:可以见2020-01算法刷题集,参考题目0113巨人排队和0131会议室Ⅱ的处理流程
将所有人按照体重进行降序排列,遍历列表,实现将每一个人按照顺序进入救生艇的过程
首先创建一个救生艇列表,将救生艇的最大载重量减去当前救生艇的承重量,为剩余的载重量
当剩余载重量满足下一个人进入时,则重复以上动作
当剩余的载重量不满足下一个人进入时,则将救生艇的最大载重量减去当前救生艇的承重量再次探入救生艇列表中
列表的长度即是最少船数。
程序代码:
#0202.py-救生艇
def findindex(list):
for i in range(len(list)):
if(list[i]==1):
return i
return -1
def trueorfalse(ele,list):
tf_list = [0 for i in range(len(list))]
for i in range(len(list)):
if(list[i]>=ele):
tf_list[i] = 1
return tf_list
def run(limit,peopleList):
shipList = []
for i in range(len(peopleList)):
tf_list = trueorfalse(peopleList[i],shipList)
if(findindex(tf_list)==-1):
shipList.append(limit-peopleList[i])
else:
shipList[findindex(tf_list)]=shipList[findindex(tf_list)]-peopleList[i]
return shipList
def main():
limit = eval(input())
inputList = input().split(",")
people = []
for i in inputList:
people.append(int(i))
people.sort(reverse=True)
shipList = run(limit,people)
print(len(shipList))
main()
运行结果:

来源:CSDN
作者:末_枭
链接:https://blog.csdn.net/zhj_1121/article/details/104148429