2007: 2022级软件工程专业《数据结构与算法A》实验4:面向数字图像的Huffman编/译码器的设计与实现

解答如下:

#include <iostream>
#include <queue>
#include <vector>
#include <map>
#include <iomanip>

using namespace std;

class HuffmanNode 
{
    int value;           // 灰度值
    int frequency;       // 频率
   
public:
    HuffmanNode* left;   // 左子树
    HuffmanNode* right;  // 右子树
    HuffmanNode(int v, int f) : value(v), frequency(f), left(nullptr), right(nullptr) {}
    int getValue() const { return value; }
    int getFrequency() const { return frequency; }
    HuffmanNode* getLeft() const { return left; }
    HuffmanNode* getRight() const { return right; }
    

    
};

class CompareNodes 
{
public:
    bool operator()(HuffmanNode* a, HuffmanNode* b) 
    {
        return a->getFrequency() > b->getFrequency();
    }
};

HuffmanNode* build(map<int, int> f) 
{
    priority_queue<HuffmanNode*, vector<HuffmanNode*>, CompareNodes> pq;

    for (map<int, int>::iterator it = f.begin(); it != f.end(); ++it) 
    {
        int key = it->first;
        int value = it->second;
        pq.push(new HuffmanNode(key, value));
    }


    while (pq.size() > 1) {
        HuffmanNode* left = pq.top();
        pq.pop();
        HuffmanNode* right = pq.top();
        pq.pop();

        HuffmanNode* parent = new HuffmanNode(-1, left->getFrequency() + right->getFrequency());
        parent->left = left;
        parent->right = right;
        pq.push(parent);
    }

    return pq.top();
}

void make(HuffmanNode* root, string code, map<int, string>& codes) {
    if (!root) {
        return;
    }

    if (root->getValue() != -1) {
        codes[root->getValue()] = code;
    }

    make(root->getLeft(), code + "0", codes);
    make(root->getRight(), code + "1", codes);
}

int main() {
    int h, w;
    while (cin >> h >> w && h != 0 && w != 0) {
        map<int, int> f;

        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                int value;
                cin >> value;
               f[value]++;
            }
        }

        HuffmanNode* root = build(f);
        map<int, string> huffmanCodes;
        make(root, "", huffmanCodes);

        int before = 0;
        int after = 0;

        for (map<int,int>::iterator it=f.begin();it!=f.end();it++)
        {
            int value = (*it).first;
            int frequency = (*it).second;
            before += 8 * frequency;
            after += frequency * huffmanCodes[value].length();
        }

        double rate = static_cast<double>(before) /after;
        cout << fixed << setprecision(2) << "Huffman编码的压缩比为 " << rate << ":1" << endl;
    }

    return 0;
}
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值