本题实现哈夫曼编码,使用优先队列即可。
#include <iostream>
#include <string>
#include <queue>
#include <functional>
#include <iomanip>
using namespace std;
int num[30]; //各字符出现的次数
int sum; //哈夫曼编码总长度
priority_queue <int, vector<int>, greater<int>> q; //升序优先队列
void encode(); //实现哈夫曼编码
int main()
{
string str;
while (cin >> str)
{
if (str == "END")
break;
sum = 0;
memset(num, 0, sizeof(num));
while (!q.empty()) //将之前计算中队列剩余元素清空(只有一个元素时会剩余)
q.pop();
for (int i = 0; i < str.length(); i++)
{
if (str[i] == '_')
num[26]++;
else
num[str[i] - 'A']++;
}
for (int i = 0; i < 30; i++)
{
if (num[i] > 0)
q.push(num[i]); //入优先队列,按照大小顺序
}
encode();
cout << str.length() * 8 << " " << sum << " " << fixed << setprecision(1) << str.length()*8.0 / sum << endl;
}
return 0;
}
void encode()
{
int a, b;
while (q.size() > 1)
{
a = q.top();
q.pop();
b = q.top();
q.pop();
//编码长度为层数*出现的次数,将a+b的和入队列,之后再加到sum上,相当于乘以层数
sum += (a + b);
q.push(a + b);
}
if (sum == 0) //队列中只有一个元素
sum = q.top();
}
继续加油。
来源:https://blog.csdn.net/Intelligence1028/article/details/102657446