【问题描述】使用贪心算法求解Huffman编码问题,具体来说就是,根据每个字符的出现频率,使用最小堆构造最小优先队列,构造出字符的最优二进制表示,即前缀码。在程序开始说明部分,简要描述使用贪心算法求解Huffman编码问题的算法过程。
【输入形式】在屏幕上输入字符个数和每个字符的频率。
【输出形式】每个字符的Huffman编码。
【样例输入】
6
45 13 12 16 9 5
【样例输出】
a 0
b 101
c 100
d 111
e 1101
f 1100
【样例说明】
输入:字符个数为6,a至f每个字符的频率分别为:45, 13, 12, 16, 9, 5。
输出:每个字符对应的Huffman编码。
【评分标准】根据输入得到准确的输出。
基本思想:
使用优先队列维护一个最小堆,根据哈夫曼树规则构建树结构
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 1005;
struct Node{
int x = 0, l = -1, r = -1, i = -1;
friend bool operator < (Node a, Node b) {
return a.x > b.x;
}
}a[maxn];
int n = 0, l = 0;
priority_queue<Node> q;
string b[maxn];
void BackTrace(int h, string s) {
if(a[h].i < n) {
b[h] = s;
return;
}
BackTrace(a[h].l, s+'0');
BackTrace(a[h].r, s+'1');
}
int main() {
cin >> n;
for(int i = 0; i < n; ++i) {
cin >> a[i].x;
a[i].i = i;
q.push(a[i]);
}
l = n;
while(q.size() != 1) {
Node n1 = q.top(); q.pop();
Node n2 = q.top(); q.pop();
a[++l].x = n1.x + n2.x;
a[l].i = l;
a[l].l = n1.i;
a[l].r = n2.i;
q.push(a[l]);
}
int head = q.top().i;
BackTrace(head, "");
for(int i = 0; i < n; ++i) {
char c = i + 'a';
cout << c << " " << b[i] << endl;
}
return 0;
}