优先队列实现哈夫曼编码(贪心法)

构造哈夫曼树及输出哈夫曼编码,优先队列构造最小堆实现
Windows下输入结束方法:Enter,Ctrl+Z,Enter

运行结果如下:
运行结果

#include <fstream>
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;

typedef struct treeNode {
    treeNode * lchild, * rchild;
    char ch;
    int weight;
    string huffCode;
    //带初始化列表得到构造函数
    treeNode():lchild(NULL),rchild(NULL),ch('\0'),weight(0),huffCode(""){}
}treeNode,*tree;

//遍历哈夫曼树,打印哈夫曼编码
void createHuffCode(treeNode * root) {
        if (root->lchild) {
            root->lchild->huffCode =root->huffCode+ "0";
            createHuffCode(root->lchild);
        }
        //如果是叶子结点,打印
        if (!(root->lchild) && !(root->rchild)) {
            cout << root->ch << " ";


                cout << root->huffCode;

            cout << endl;
        }
        if (root->rchild) {
            root->rchild->huffCode = root->huffCode + "1";
            createHuffCode(root->rchild);
        }
    }


//自定义比较体
struct cmp {
    bool operator() (treeNode *a, treeNode * b) {
        return a->weight > b->weight;
    }
};
//最小堆
priority_queue < treeNode*, vector<treeNode*>, cmp > pque;


void createHuffTree() {

        vector<int> vfreq;     
        vector<char> vch;

        //文件读写
        //ifstream ifs;
        //ifs.open("huffman.in");
        //while (!ifs.eof()) {  
        //  char ch_temp;
        //  int freq_temp;
        //  ifs >> ch_temp;
        //  ifs >> freq_temp;
        //  vch.push_back(ch_temp);
        //  vfreq.push_back(freq_temp);
        //}
        //ifs.close();

        //标准输入输出流读写
        char ch_temp;
        int freq_temp;
        while (cin>>ch_temp >> freq_temp) {
            vch.push_back(ch_temp);
            vfreq.push_back(freq_temp);
        }

        for (int i = 0; i < vch.size(); i++) {
            treeNode * t = new treeNode;
            t->ch = vch[i];
            t->weight = vfreq[i];
            pque.push(t);
        }

    //依次找出权值最小的两个结点
    while (pque.size() != 1) {
        treeNode *a, *b;
        a = pque.top();
        pque.pop();
        b = pque.top();
        pque.pop();
        treeNode * temp = new treeNode;
        temp->weight = a->weight + b->weight;
        temp->lchild = a;       //连成一棵树
        temp->rchild = b;
        pque.push(temp);
    }

    createHuffCode(pque.top());
}


int main() {
    createHuffTree();
    return EXIT_SUCCESS;
}
展开阅读全文

没有更多推荐了,返回首页