实验11哈夫曼编码

问题:

给定字符集和每个字符出现的频率,构造最优前缀码。

解析:

贪心构造最优前缀码,按照频率从小到大排序,最小两个字符频率相加后产生新的字符频率加入优先队列中,频率越小离树根越远。

设计(核心代码):

 1 while (q.size() > 1) {
 2     x = q.top();
 3     q.pop();
 4     x += q.top();
 5     q.pop();
 6     q.push(x);
 7 }
 8 if (!q.empty()) {
 9     ans = q.top();
10     q.pop();
11 }

分析:

复杂度:$O(n*log(n))$

源码:

https://github.com/Big-Kelly/Algorithm

 1 #include<bits/stdc++.h>
 2 #include <set>
 3 #include <map>
 4 #include <stack>
 5 #include <cmath>
 6 #include <queue>
 7 #include <cstdio>
 8 #include <string>
 9 #include <vector>
10 #include <cstring>
11 #include <iostream>
12 #include <algorithm>
13 
14 #define ll long long
15 #define PLL pair<ll,ll>
16 #define PII pair<int,int>
17 #define bug printf("*********
")
18 #define FIN freopen("input.txt","r",stdin);
19 #define FON freopen("output.txt","w+",stdout);
20 #define IO ios::sync_with_stdio(false),cin.tie(0)
21 #define ls root<<1
22 #define rs root<<1|1
23 
24 using namespace std;
25 const int inf = 0x3f3f3f3f;
26 const ll Inf = 1e14 + 7;
27 const int maxn = 1e5 + 5;
28 const int mod = 1e9 + 7;
29 
30 int n, x;
31 priority_queue<int, vector<int>, greater<int> >q;
32 
33 int main() {
34     while (cin >> n) {
35         int ans = 0;
36         for (int i = 1; i <= n; ++i) {
37             cin >> x;
38             q.push(x);
39         }
40         while (q.size() > 1) {
41             x = q.top();
42             q.pop();
43             x += q.top();
44             q.pop();
45             q.push(x);
46         }
47         if (!q.empty()) {
48             ans = q.top();
49             q.pop();
50         }
51         cout << ans << endl;
52     }
53 }
View Code
原文地址:https://www.cnblogs.com/zhang-Kelly/p/12915634.html