Huffman编码(哈夫曼编码),
来源:互联网 发布:淘宝小众服装品牌 编辑:程序博客网 时间:2024/06/05 19:41
实现Huffman编码是用贪心算法来实现的,。实现Huffman最好的数据结构时优先级队列。整个算法的时间复杂度可以达到nlg(n),这里为了简单,没有实现最小堆,而使用的是STL中的set,通过实现正确的比较函数对象,每次可以取得优先级(字符出现频度最低)最大的值。但是这里的时间复杂度却提高了,因为操作set的选择时,时间复杂度时lgn,但是随着选择的,选择“未被访问的最高优先级的两个元素(flag=0)”的探测次数也为增大,平均探测次数是n/2,因此最后实现Huffman的时间复杂度将是n^2lg(n)。当然也可以通过记录每次选择元素时其在set中的位置(偏移量),下次选择时直接通过这个偏移量找到合适位置,探测的时间复杂度将会是1,最后实现Huffman的时间复杂度也可以达到nlog(n)。
具体代码如下:
- #include <iostream>
- #include <set>
- using namespace std;
- struct Node
- {
- int fu;
- int flag;
- struct Node *lc;
- struct Node *rc;
- };
- struct compare_node
- {
- bool operator()(const Node* node1,const Node *node2)const
- {
- return node1->fu < node2->fu;
- }
- };
- set < Node *,compare_node> queue;
- const int N = 6;
- int s[N];
- int f[N];
- struct Node *huffman()
- {
- int i = 0;
- while(i<N-1)
- {
- Node *child[2];
- set< Node *,compare_node>::iterator it = queue.begin();
- int lr = 0;
- while(it!=queue.end() && lr <2)
- {
- if((*it)->flag ==0)
- {
- child[lr] =*it;
- (*it)->flag = 1;
- lr ++;
- }
- it++;
- }
- Node *parent = new Node;
- parent->flag = 0;
- parent->lc = child[0];
- parent->rc = child[1];
- parent->fu = child[0]->fu + child[1]->fu;
- queue.insert(parent);
- i++;
- }
- int count = queue.size();
- set <Node*>::reverse_iterator rit = queue.rbegin();
- if(rit!=queue.rend())
- return *rit;
- else
- return NULL;
- }
- void print(Node * root,int c)
- {
- if(root == NULL)
- return;
- else
- {
- if( root->lc != NULL)
- {
- s[c++] = 0;
- print(root->lc,c);
- }
- if(root->rc!=NULL)
- {
- c--;
- s[c++]=1;
- print(root->rc,c);
- }
- if(root->lc == NULL && root->rc == NULL)
- {
- cout << root->fu <<" ";
- int i =0;
- for(i=0;i<c;i++)
- cout << s[i];
- cout << endl;
- }
- }
- }
- int main()
- {
- int i =0;
- Node *p = NULL;
- for(i=0;i<N;i++)
- {
- cin>>f[i];
- p = new Node;
- p->flag = 0;
- p->fu = f[i];
- p->lc = NULL;
- p->rc = NULL;
- queue.insert(p);
- }
- Node *node = huffman();
- print(node,0);
- }
0 0
- Huffman编码(哈夫曼编码),
- 哈夫曼(Huffman )编码
- 哈夫曼编码(Huffman)
- Huffman编码(Huffman树)
- 哈夫曼(Huffman)编码
- 哈夫曼编码-Huffman
- Huffman 编码 (贪心)
- Huffman(霍夫曼)编码
- 哈夫曼(huffman)树和哈夫曼编码
- 哈夫曼(huffman)树和哈夫曼编码
- [非原创] 哈夫曼(Huffman )编码
- poj 1521 Entropy huffman(哈夫曼)编码
- Matlab 图像处理-哈夫曼编码(huffman)
- 哈夫曼(Huffman)编码与解码
- huffman编码
- huffman编码
- HUFFMAN 编码
- Huffman编码
- HDU 1257 最少拦截系统(DP和贪心)
- Java 多线程(三)线程间的通信jdk1.5中Lock,Condition---生产者消费者为例
- iOS UI 16 图片加载第三方 SDwebimage
- iOS UI 17 网络请求封装
- HDU 4284 —— Travel 状压dp|DFS+Floyd
- Huffman编码(哈夫曼编码),
- 如何与AppStore团队有效沟通
- Android Serializable与Parcelable 用法
- Growth Hacking背后,数据分析平台的架构调整
- iOS UI 17 初级数据持久化
- 对KLT,主成分分析(PCA)算法的理解
- ExpendableListActivity控件的使用
- Git使用
- 提取行间事件