哈弗曼编码题
如果真的去构建一颗哈夫曼树,那就太麻烦了
而且根据题目要求的输出可以知道没有必要构造一个完整的树
根据哈夫曼树的特点,可知道可以用优先队列实现功能
每次从队列中取两个最小的,将其和再放入队列
一直重复这个操作知道队列中只剩一个元素
代码如下:
#include <queue>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define MAXN 10010
#define ll long long
using namespace std;
string str;
priority_queue<int , vector<int>, greater<int> > q;
//greater<int>为从小到大队列
//less<int>为从大到小队列
int main(void) {
while(cin>>str && str!="END") {
sort(str.begin(), str.end());
char ch = str[0];
int times = 0;
for(int i=0; i<str.size(); ++i) {
if(ch == str[i]) {
times++;
}
else {
q.push(times);
times = 1;
ch = str[i];
}
}
q.push(times);
int ans1 = str.size()*8;
int ans2 = 0;
int a, b;
if(q.size() == 1) {
ans2 = q.top();
}
while(1) {
a = q.top();
q.pop();
if(q.empty())//边界条件为队列中只剩一个元素
break;
b = q.top();
q.pop();
ans2 += (a+b);
q.push(a+b);
}
printf("%d %d %.1f\n", ans1, ans2, ans1*1.0/ans2);
}
return 0;
}