题解 | #漂流船问题#
漂流船问题
https://www.nowcoder.com/practice/0e6cb06ec63148ed952f887a787f0103
import sys # 公司组织团建活动,到某漂流圣地漂流,现有如下情况: # 员工各自体重不一,第 i 个人的体重为 people[i],每艘漂流船可以承载的最大重量为 limit。 # 每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。 # 为节省开支,麻烦帮忙计算出载到每一个人所需的最小船只数(保证每个人都能被船载)。 def boatCount(lst, limit): # 开始计算 lst.sort() if len(lst) == 1: if lst[0] <= limit: raise Exception("Max weight ecceded!") else: print(0) raise Exception("Max weight ecceded!") boat_count = 0 l_index, r_index = 0, len(lst) - 1 while l_index <= r_index: if l_index == r_index: if lst[l_index] <= limit: boat_count += 1 break else: raise Exception("Max weight ecceded!") if lst[l_index] + lst[r_index] <= limit: l_index += 1 r_index -= 1 boat_count += 1 continue else: if lst[r_index] > limit: raise Exception("Max weight ecceded!") boat_count += 1 r_index -= 1 return boat_count people = [] if __name__ == "__main__": people = input().split() for i, j in enumerate(people): try: people[i] = int(j) except: raise Exception("Wrong input") boatWeightlimit = int(input()) result = boatCount(people, boatWeightlimit) print(result)