Question and Answer from L4-M2
import heapq
def min_time_to_collect_all_candies(boxes):
# Use a min-heap to always combine the smallest two boxes
heapq.heapify(boxes)
total_time = 0
while len(boxes) > 1:
first = heapq.heappop(boxes)
second = heapq.heappop(boxes)
time_taken = first + second
total_time += time_taken
heapq.heappush(boxes, time_taken)
return total_time
# Read input
t = int(input())
for _ in range(t):
n = int(input())
boxes = list(map(int, input().split()))
result = min_time_to_collect_all_candies(boxes)
print(result)