C++基于优先队列建立链式哈夫曼树并求哈夫曼编码及WPL

优先队列指针类型自定义排序方法:

struct cmp {  // 使用仿函数(函数对象)作为Compare双参判断式
    bool operator()(const HTree &node1, const HTree &node2) {
        return node1->weight > node2->weight;
    }
};
priority_queue<HTree, vector<HTree>, cmp> q;  // 小顶堆
/*
8
7 19 2 6 32 3 21 10
*/

#include <bits/stdc++.h>
using namespace std;

typedef struct node {
    int weight;
    struct node *lchild, *rchild;
    string code;
} HTNode, *HTree;

struct cmp {  // 使用仿函数(函数对象)作为Compare双参判断式
    bool operator()(const HTree& node1, const HTree& node2) {
        return node1->weight > node2->weight;
    }
};

int WPL = 0;

HTree create_WPL(int n) {
    priority_queue<HTree, vector<HTree>, cmp> q;  // 小顶堆
    for (int i = 0; i < n; i++) {
        HTree temp = new HTNode();
        int w;
        cin >> w;
        temp->weight = w;
        temp->lchild = NULL;
        temp->rchild = NULL;
        temp->code = "";
        q.push(temp);
    }
    for (int i = 0; i < n - 1; i++) {  // 新加入结点共n-1个
        HTree node1 = q.top();
        q.pop();
        HTree node2 = q.top();
        q.pop();
        HTree newNode = new HTNode();
        newNode->weight = node1->weight + node2->weight;
        newNode->lchild = node1;
        newNode->rchild = node2;
        newNode->code = "";
        q.push(newNode);
        WPL += newNode->weight;  // 各个父节点的频度值加和即带权路径长度
    }
    return q.top();
}

vector<string> code;

void pre_coding(HTree node, string str) {  // 前序遍历并编码
    if (node->lchild == NULL && node->rchild == NULL) {
        node->code = str;
        code.push_back(str);
    } else {
        pre_coding(node->lchild, str + "0");
        pre_coding(node->rchild, str + "1");
    }
}

void levle_order(HTree root) {  // 层次遍历
    queue<HTree> qu;
    qu.push(root);
    HTree p = root;
    while (!qu.empty()) {
        p = qu.front();
        cout << p->weight << " ";
        qu.pop();
        if (p->lchild)
            qu.push(p->lchild);
        if (p->rchild)
            qu.push(p->rchild);
    }
}

int main() {
    int n;
    cin >> n;
    HTree H;
    H = create_WPL(n);
    levle_order(H);  // 层次遍历
    cout << endl;
    pre_coding(H, "");
    sort(code.begin(), code.end());
    for (auto i : code)
        cout << i << " ";
    cout << endl;
    cout << WPL;
    return 0;
}0;
}

测试用例:

8
7 19 2 6 32 3 21 10

输出结果:

100 40 60 19 21 28 32 11 17 5 6 7 10 2 3
00 01 10000 10001 1001 1010 1011 11
261

即:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月初XH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值