算法导论 ch16 贪心算法 霍夫曼编码

1. source codes

#include <iostream> #include <queue> using namespace std; class TreeNode { private: char data; int frq; TreeNode *left; TreeNode *right; public: TreeNode(char c = '*', int f = 0, TreeNode *l = NULL, TreeNode *r = NULL) : data(c), frq(f), left(l), right(r) { } TreeNode(TreeNode *a, TreeNode *b) : data('*'), frq(a->frq + b->frq), left(a), right(b) { } friend ostream& operator<<(ostream &os, TreeNode *t); template<class T> friend class cmp; }; template<class T> class cmp { public: bool operator()(T a, T b) { return a->frq > b->frq; } }; ostream& operator<<(ostream &os, TreeNode *t) { os << "node char is "<< t->data<< ", frequency is "<< t->frq<< endl; // if (t->left) { // os << " left child "<< endl; // os << t->left; // } // if (t->right) { // os << " right child "<< endl; // os << t->right; // } return os; } /* * tr: an array storing the data * n: array length */ void huffman(priority_queue<TreeNode*, vector<TreeNode*>, cmp<TreeNode*> > pq) { int n = pq.size(); for (int i = 1; i < n; i++) { TreeNode* x = pq.top(); cout << "x: " << x << endl; pq.pop(); TreeNode* y = pq.top(); cout << "y: " << y << endl; pq.pop(); TreeNode* z = new TreeNode(x, y); pq.push(z); } TreeNode *z = pq.top(); cout << z << endl; } int main() { priority_queue<TreeNode*, vector<TreeNode*>, cmp<TreeNode*> > pq; pq.push(new TreeNode('f', 5)); pq.push(new TreeNode('e', 9)); pq.push(new TreeNode('c', 12)); pq.push(new TreeNode('b', 13)); pq.push(new TreeNode('d', 16)); pq.push(new TreeNode('a', 45)); huffman(pq); }

2. test result

x: node char is f, frequency is 5 y: node char is e, frequency is 9 x: node char is c, frequency is 12 y: node char is b, frequency is 13 x: node char is *, frequency is 14 y: node char is d, frequency is 16 x: node char is *, frequency is 25 y: node char is *, frequency is 30 x: node char is a, frequency is 45 y: node char is *, frequency is 55 node char is *, frequency is 100

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值