算法分析与实践-作业11

哈夫曼编码

2. 解析

构造最优前缀码的贪心算法就是哈夫曼算法(Huffman)

3. 设计

 1 #include<stdio.h>
 2 #include<queue>
 3 #include<vector>
 4 using namespace std; 
 5 #define ll long long
 6 int main() {
 7     int n;
 8     while (scanf("%d", &n) != EOF) {
 9         priority_queue<ll, vector<ll>, greater<ll> >q;
10         ll res = 0;
11         for (int i = 1; i <= n; ++i) {
12             ll x;
13             scanf("%lld", &x);
14             q.push(x);
15         }
16         while (1) {
17             ll a = q.top();
18             q.pop();
19             if (q.empty())break;
20             ll b = q.top();
21             q.pop();
22             res += a + b;
23             q.push(a + b);
24         }
25         printf("%lld
", res);
26     }
27 }

4. 分析

O(nlogn)频率排序;for循环O(n),插入操作O(logn),算法时间复杂度是O(nlogn)

5. 源码

https://github.com/JayShao-Xie/algorithm-work/blob/master/Huffman.cpp

原文地址:https://www.cnblogs.com/JayShao/p/12891433.html