poj 1521 Entropy(优先队列)

哈弗曼编码题

如果真的去构建一颗哈夫曼树,那就太麻烦了

而且根据题目要求的输出可以知道没有必要构造一个完整的树

根据哈夫曼树的特点,可知道可以用优先队列实现功能

每次从队列中取两个最小的,将其和再放入队列

一直重复这个操作知道队列中只剩一个元素

代码如下:

#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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值