算法分析 - 哈夫曼编码(贪心算法) (新)

【问题描述】使用贪心算法求解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;
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值