Huffman编码

#include <iostream>
#include <stack>
#include <map>
#include <iterator>
#include <vector>
using namespace std;

typedef struct huffman_node {
    char c;
    int w;
    string huffman_code;
    struct huffman_node* lchild;
    struct huffman_node* rchild;
    huffman_node() {
        c = ' '; w = 0; huffman_code = ""; lchild = rchild = 0;
    }
} hn;

map<char, int> word_frequency; // frequency_table
vector<hn*> words;
// the root of the tree

void read_from_file() {
    freopen("/Users/wanglang/Documents/C++/Tree_of_mooc/Tree_of_mooc/in.txt", "r", stdin);
    char c;
    while(cin >> c) {
        word_frequency[c]++;
    }
    map<char, int>::iterator it;
    for(it = word_frequency.begin(); it != word_frequency.end(); it++) {

        hn * p = new huffman_node;
        p->c = it->first; p->w = it->second;
        p->lchild = p->rchild = NULL;
        words.push_back(p);
    }
}
int cmp(hn * p1, hn * p2) {
    return p1->w < p2->w;
}
hn * build() {
    sort(words.begin(), words.end(), cmp);
    vector<hn*>::iterator it = words.begin();
    while((int)words.size() > 1) {
        vector<hn*>::iterator it2 = it+1;
        hn * p = new huffman_node();
        p->c = '*'; p->w = (*it)->w + (*it2)->w;
        p->lchild = (*it); p->rchild = (*it2);
        words.erase(it); words.erase(it);
        words.push_back(p);
        sort(words.begin(), words.end(), cmp);
    }
    hn * root = *(words.begin());
    return root;
}

void recursion(hn * root){
    if(root->lchild) {
        root->lchild->huffman_code = root->huffman_code + "1";
        recursion(root->lchild);
    }
    if(root->rchild) {
        root->rchild->huffman_code = root->huffman_code + "0";
        recursion(root->rchild);
    }
}
void tran_pre(hn * root) {
    if(root->c != '*') {
        cout << root->c << " " << root->w << " "  << root->huffman_code << endl;
    }
    if(root->lchild) tran_pre(root->lchild);
    if(root->rchild) tran_pre(root->rchild);
}
int main() {
    read_from_file();
    hn * root = build();
    recursion(root);
    tran_pre(root);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值