#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;
}
Huffman编码
最新推荐文章于 2023-10-18 00:20:58 发布