Huffman 编码 + 优先队列【算法+数据作业题】

Huffman 编码【算法+数据作业题】

题目:

已知字符出现频率、固定编码如下表,请编程实现可变长度编码,要求采用Huffman编码。

Huffman 编码 + 优先队列【算法+数据作业题】_第1张图片

实现代码:

#include <queue>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

struct Chara {
    char ch;
    int Freq;
    string Fix_Code, Var_Code;
};
struct Node {
    int w, id;
    Node *par, *lson, *rson;
    Node() : par(NULL), lson(NULL), rson(NULL) {};
    Node(int _w) : w(_w) {}
    bool operator < (const Node& p) const;
    bool operator > (const Node& p) const;
};
bool Node::operator < (const Node& p) const {
    return w < p.w;
}
bool Node::operator > (const Node& p) const {
    return w > p.w;
}

priority_queue<Node, vector<Node>, greater<Node> > Q;
Node* Build_HufTree(int N) {
    Node *ls, *rs, *root;
    while(!Q.empty()) {
        if(Q.size() == 1) {
            *root = Q.top();
            Q.pop();
            continue;
        }
        ls = new Node(), rs = new Node(), root = new Node();
        *ls = Q.top();
        Q.pop();
        *rs = Q.top();
        Q.pop();
        ls->par = root, rs->par = root;
        root->lson = ls, root->rson = rs, root -> w = ls -> w + rs -> w;
        Q.push(*root);
    }
    return root;
}
void Get_Code(Node *ptr, Chara *arr, string str) {
    if(ptr->lson == NULL && ptr->rson == NULL) {
        arr[ptr->id].Var_Code = str;
        printf("%c", arr[ptr->id].ch);
        return;
    }
    if(ptr->lson) Get_Code(ptr->lson, arr, (str + "0"));
    if(ptr->rson) Get_Code(ptr->rson, arr, (str + "1"));
}
// 释放内存
void Release(Node *ptr) {
    if(ptr->lson == NULL && ptr->rson == NULL) {
        delete ptr;
        return;
    }
    if(ptr->lson) Release(ptr->lson);
    if(ptr->rson) Release(ptr->lson);
}
int main() {
//    freopen("input.txt", "r", stdin);
    int N;

    cout<<"请输入需要编码字符的个数N: "<<endl;
    cin >> N;

//    N 个叶子的二叉树含 非叶子节点的数目为 N - 1 , 总节点为 2*N - 1
    Chara *chs = new Chara[N];

    cout << "请依次输入N个字符、每个字符的频率、以及他的固有编码~"<<endl;

    cin.ignore();

    Node now;
    for(int i = 0; i < N; i++) {
        Chara &c = chs[i];
        cin >> c.ch >> c.Freq >> c.Fix_Code;
        now.id = i;
        now.w = c.Freq;
        Q.push(now);
    }

    Node *root = Build_HufTree(N);
    Get_Code(root, chs, "");

    cout<<"依次输出这N个字符的Huffman编码:\n";
    for(int i = 0; i < N; i++) {
        cout << "The Huffman Code of [" << chs[i].ch << "] is : " << chs[i].Var_Code << endl;
    }
    Release(root);
    delete chs;
    return 0;
}
/**
Sample Input:
6
a 45 000
b 13 001
c 13 010
d 16 011
e 9  100
f 5  101
*/

运行截图:


你可能感兴趣的:(Huffman 编码 + 优先队列【算法+数据作业题】)