算法导论 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

你可能感兴趣的:(c,算法,OS,null,Class)