POJ 1521 熵 定长编码和变长编码的比较(huffman)
2013-08-24 18:38
363 查看
#include<iostream> #include<queue> #include<string> #include<vector> #include<algorithm> #include<cstdio> #include<fstream> using namespace std; int main() { string text; int count[128]; while (cin >> text && text != "END") { int i; int n = text.size(); memset(count, 0, sizeof count); for (i = 0; i < n; i++) { count[text[i]]++; } priority_queue<int, vector<int>, greater<int> > que; for (i = 0; i <= 127; i++) { if (count[i] != 0) { que.push(count[i]); } } int asclen, hfmlen; asclen = n * 8; hfmlen = 0; if (que.size() == 1) /* only one char appear */ { hfmlen = que.top(); que.pop(); // cout << asclen << " " << hfmlen << " " << (float)asclen / hfmlen << "\n"; printf("%d %d %.1f\n", asclen, hfmlen, (float)asclen / hfmlen); continue; } while (true) /* This is the key part */ { int first, second; if (que.empty()) break; first = que.top(); que.pop(); if (que.empty()) break; second = que.top(); que.pop(); que.push(first + second); hfmlen += (first + second); } //cout << asclen << " " << hfmlen << " " << (float)asclen / hfmlen << "\n"; printf("%d %d %.1f\n", asclen, hfmlen, (float)asclen / hfmlen); } return 0; }
输入一串字符(无空格),分别计算对这些字符进行huffman编码的编码长度和ascii编码的长度。
并将两者进行比较。借助c++ STL中的优先级队列很容易实现。
感觉cout 的输出格式不好控制。
for (i = 0; i <= 127; i++) { if (count[i] != 0) { que.push(count[i]); } }
这个循环书写上除了个错误,127写成了n是个笔误,造成了很多困扰。
编码总长L = SUM( len[i]*freq[i] );
在huffman树中的体现,应该注意理解。
相关文章推荐
- poj 1521(ENTROPY) huffman 编码
- POJ 1521 , Entropy , Huffman
- poj1521 huffman
- Huffman和Priority_queue 解决POJ 1521
- 贪心法 Fence Repair POJ 3253 霍夫曼(Huffman)编码原理 acmclub 12326
- poj 1521 Entropy huffman(哈夫曼)编码
- poj 1521_huffmanb code
- 编码节点poj 1521 Entropy huffman(哈夫曼)编码
- poj-2567 prufer 编码
- POJ 3253 修理栅栏 - (贪心 Huffman)
- poj 3253 Fence Repair(Huffman问题,优先队列priority_queue)
- Huffman 编码简介
- python 实现的huffman 编码压缩,解码解压缩
- poj 2413 How many Fibs? 大数累加模板+字符串模拟大数比较大小
- POJ推荐50题 1. 标记“难”和“稍难”的题目可以看看,思考一下,不做要求,当然有能力的同学可以直接切掉。 2. 标记为 A and B 的题目是比较相似的题目,建议大家两个一起做,可以对比总结,
- 霍夫曼编码,Huffman
- MPEG2与MPEG4在视频编码的简单比较
- MPEG2和MPEG4视频编码的比较
- poj1521
- Huffman 编码算法之 Java 实现