算法导论第十五章--霍夫曼编码
来源:互联网 发布:任盈盈 知乎 编辑:程序博客网 时间:2024/06/10 01:04
这道题纠结了一天,本想用简单点的方法实现,可是反而弄巧成拙。不过通过写该代码学会了如何使用优先级队列,对优先级队列有了进一步的了解。代码如下:
其中难度较大的是优先级队列的使用,详细的使用方法请参考博主的另一篇文章优先级队列的基本应用
//在优先级队列中存入指针类型的节点#include<iostream>#include<queue>#include<string>using namespace std;class Comapre;class Node{private:friend Comapre;int key;char ch;Node*left;Node*right;public:Node(int num,char c):key(num),ch(c),left(NULL),right(NULL){}//bool lessthan (const Node* node) const{return key>node->key;}int GetKey(){return key;}char GetChar(){return ch;}Node*GetLeft(){return left;}Node*GetRight(){return right;}void SetLeft(Node*node){this->left=node;}void SetRight(Node*node){this->right=node;}void SetChar(char a){ch=a;}void SetKey(int a){key=a;}};class Comapre{public://因为优先级队列中传递的指针,所以不能直接在Node类里重载比较运算符bool operator () (Node*node1,Node*node2){bool flag=node1->lessthan(node2);return flag;}};//使用优先级队列存储元素,优先级队列能保证队列最顶端的是按照键值key排列的最小的元素Node* Huffman(priority_queue<Node*,vector<Node*>,Comapre>que){//重复将最顶端的两个元素拿出合并之后再放入队列中while(que.size()>1){Node *node=new Node(0,0);node->SetLeft(que.top());que.pop();node->SetRight(que.top());que.pop();node->SetKey(node->GetLeft()->GetKey()+node->GetRight()->GetKey());que.push(node);}return que.top();}//利用中序遍历的方法输出霍夫曼编码//思路是每向左指一个节点st添加0,每向右指一个节点添加1,没迭代完一次要退出st最后一个元素//用到了string的pop_back函数void Inorder(Node* node,string st){if(node==NULL){return ;}else{if(node->GetLeft()!=NULL){st+='0';}Inorder(node->GetLeft(),st);if(node->GetLeft()==NULL&&node->GetRight()==NULL){cout<<node->GetChar()<<"'s code is :";for(int i=0;i<st.length();i++){cout<<st[i];}cout<<endl;}st.pop_back();if(node->GetRight()!=NULL)st+='1';Inorder(node->GetRight(),st);}}//将开辟的空间清空,不然会导致内存泄露void Delete(Node*node){if(node==NULL){return ;}Delete(node->GetLeft());Delete(node->GetRight());delete node;}int main(){string st;Node*n[6];n[0]=new Node(5,'f');n[1]=new Node(9,'e');n[2]=new Node(16,'d');n[3]=new Node(12,'c');n[4]=new Node(13,'b');n[5]=new Node(45,'a');priority_queue<Node*,vector<Node*>,Comapre>qu;int i;for(i=0;i<6;i++){qu.push(n[i]);}Node* R =Huffman(qu);Inorder(R,st);Delete(R);return 0;}
- 算法导论第十五章--霍夫曼编码
- 算法导论第十五章
- 算法导论第十五章习题15.4-2
- 算法导论第十五章习题15.4-5
- 算法导论第十五章15.2-4
- 算法导论第十五章-装配线高度算法实现
- 算法导论学习笔记-第十五章-动态规划
- 算法导论第十五章习题15.1-1c++代码实现
- 算法导论第十五章习题15.4-4c++代码实现
- 算法导论第十五章--最优二叉查找树
- 算法导论笔记——第十五章 动态规划
- 算法导论第十五章-动态规划-Cpp代码实现
- 算法导论第十五章15-2最长回文子序列
- 算法导论第十五章(最长公共子序列)
- 算法导论 ch16 贪心算法 霍夫曼编码
- 算法导论 哈夫曼编码
- 算法导论哈夫曼编码
- 算法导论第十五章动态规划
- rh401 - 简单pxe网络引导环境的搭建
- hud 2709 Sumsets
- QT、QTE、qtopia区别
- poj 2533 最长上升子序列
- 学习lisp
- 算法导论第十五章--霍夫曼编码
- vs.net 2005, 没有找到MSVCR80D.dll的完美解决方案
- c/c++ error C2614: illegal member initialization: is not a base or member
- 国内pinterest发展介绍------瀑布流效果
- iPhone开发经典语录集锦
- proxool配置
- DBCC命令1:维护
- Linux文件属性
- Android 4.0 Launcher2源码分析——导入eclipse进行调试