题解 | 【模板】哈夫曼编码

【模板】哈夫曼编码

https://www.nowcoder.com/practice/4c0419eb07c840ca8402e4f2a52cfd49

import heapq

n = int(input())
frequencies = list(map(int, input().split()))


if n == 1:
    print(frequencies[0])
    exit()

# 使用最小堆
heap = frequencies[:]
heapq.heapify(heap)

total = 0

while len(heap) > 1:
    # 取出两个最小的频率
    first = heapq.heappop(heap)
    second = heapq.heappop(heap)
    
    # 合并这两个频率
    combined = first + second
    total += combined
    
    # 将合并后的频率放回堆中
    heapq.heappush(heap, combined)

print(total)

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务