题解 | 哈夫曼编码

哈夫曼编码

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

# 编码后字符串的长度等于原始的频率乘以编码长度再求和
import heapq
n = int(input())
a = list(map(int, input().split()))
heapq.heapify(a)
total_length = 0
while len(a)>1:
    first = heapq.heappop(a)
    second = heapq.heappop(a)
    combile = first + second
    # 每多一层,编码长度就会+1
    # 那么字符串长度就需要再原来的基础上多一倍原始的频率
    # first和second都需要增加
    # 所以加上combile即可
    total_length += combile
    heapq.heappush(a,combile)
print(total_length)

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:00
点赞 评论 收藏
分享
05-22 09:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务