题目链接:https://www.luogu.com.cn/problem/P1090
本题运用贪心算法的思想,根据题目要求,每次选择最少的两堆果子合并即可,先对果子数量进行排序,每次选择最少的两堆,再把合并后的果子在数组中找到其应该在的位置(二分),对数组进行维护,使每次操作完后数组均是升序排列
def binary_search(arr,item):
low=0
high=len(arr)-1
while low <= high:
mid=int((low+high)/2)
guess=arr[mid]
if guess < item:
low = mid + 1
else:
high = mid - 1
return low
n = int(input())
fruit = [int(i) for i in input().split()]
fruit.sort()
ans = 0
while len(fruit) > 1:
mnn = fruit[0] + fruit[1]
i = binary_search(fruit,mnn)
ans += mnn
fruit = fruit[2:i] + [mnn] + fruit[i:]
print(ans)