算法分析与实践-作业11

哈夫曼编码

算法分析与实践-作业11_第1张图片

2. 解析

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

3. 设计

 1 #include
 2 #include
 3 #include
 4 using namespace std; 
 5 #define ll long long
 6 int main() {
 7     int n;
 8     while (scanf("%d", &n) != EOF) {
 9         priority_queue, greater >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\n", 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

 

你可能感兴趣的:(算法分析与实践-作业11)