您的位置:首页 > 编程语言 > C语言/C++

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树中的体现,应该注意理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ POJ 贪心