计算WPL

本文介绍了如何使用Huffman编码对给定符号按频率构建哈夫曼树,并计算其带权路径长度(WPL)。通过优先队列实现树的构建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Huffman编码是通信系统中常用的一种不等长编码,它的特点是:能够使编码之后的电文长度最短。

更多关于Huffman编码的内容参考教材第十章。

输入:
    第一行为要编码的符号数量n
    第二行~第n+1行为每个符号出现的频率

输出:
    对应哈夫曼树的带权路径长度WPL

测试输入期待的输出时间限制内存限制额外进程
测试用例 1以文本方式显示
  1. 5↵
  2. 7↵
  3. 5↵
  4. 2↵
  5. 4↵
  6. 9↵
以文本方式显示
  1. WPL=60↵
1秒64M0
测试用例 2以文本方式显示
  1. 5↵
  2. 2↵
  3. 4↵
  4. 2↵
  5. 3↵
  6. 3↵
以文本方式显示
  1. WPL=32↵
1秒64M0

代码如下:

#include <iostream>
#include <queue>
using namespace std;
struct HFTree
{
    int weight;
    HFTree *left;
    HFTree *right;
    HFTree(int weight) : weight(weight), left(nullptr), right(nullptr) {}
};
auto compare = [](HFTree *left, HFTree *right)
{
    return (left->weight > right->weight);
};
int Calculate(HFTree *root, int depth = 0)
{
    if (!root)
        return 0;
    if (!root->left && !root->right)
        return depth * root->weight;
    return Calculate(root->left, depth + 1) + Calculate(root->right, depth + 1);
}

int main()
{
    int n;
    cin >> n;
    priority_queue<HFTree *, vector<HFTree *>, decltype(compare)> Queue(compare);
    for (int i = 0; i < n; ++i)
    {
        int weight;
        cin >> weight;
        Queue.push(new HFTree(weight));
    }
    while (Queue.size() != 1)
    {
        HFTree *left = Queue.top();
        Queue.pop();
        HFTree *right = Queue.top();
        Queue.pop();
        int sum = left->weight + right->weight;
        HFTree *top = new HFTree(sum);
        top->left = left;
        top->right = right;
        Queue.push(top);
    }
    cout << "WPL=" << Calculate(Queue.top()) << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值