You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
701 B

11 months ago
# -*- coding: utf-8 -*-
# Time : 2023/11/23 15:08
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : demo1.py
import heapq
def huffman_cost(nums):
heapq.heapify(nums) # 将列表转换为小顶堆
total_cost = 0
while len(nums) > 1:
# 从堆中取出最小的两个数
min1 = heapq.heappop(nums)
min2 = heapq.heappop(nums)
# 将两个数的和加入堆中
heapq.heappush(nums, min1 + min2)
# 累加费用
total_cost += min1 + min2
return total_cost
# 读取输入
n = int(input())
nums = list(map(int, input().split()))
# 计算 Huffman 树的总费用并输出
result = huffman_cost(nums)
print(result)