hdu1053 哈弗曼编码

该博客探讨了如何计算哈弗曼编码的长度,无需实际构建编码树。针对字符串'AAAAABCD',通过示例说明编码总长度为13。提出了两种效率为nlogn的方法:一是使用排序,二是运用有限队列来解决这个问题。
摘要由CSDN通过智能技术生成

题目链接 Entropy


只需要求编码长度,不要求输出编码结果,所以不需要建树

AAAAABCD,如图


总的编码长度=len(B)+len(C)+len(D)+5*len(A)=3+3+2+5*1=13


两种写法,都是nlogn

(1)利用sort排序

#include<stdio.h>
#include<memory.h>
#include<string.h>
#include<algorithm>

using namespace std;

char str[1005];
int num[27];
bool cmp(int a, int b){
    return a > b;
}
int main()
{
    //freopen("in.txt", "r", stdin);
    while (scanf("%s", str) != EOF&&strcmp(str, "END")){
        memset(num, 0, sizeof(num));
        int len = strlen(str);
        for (int i = 0; i < len; ++i){
            if (str[i] == '_')num[26]++;
            else num[str[i] - 'A']++;
        }
        sort(num, num + 27, cmp);
        int n = 26;
        while (!num[n])n--;
        int ans = 0;
        if (n == 0){ ans = num[0]; }//注意这里!!
        else for (int i = n; i >= 1; --i) {
            num[i - 1] += num[i];
            ans += num[i - 1];
            sort(num, num + i + 1, cmp);
        }
        
        printf("%d %d %.1f\n", len * 8, ans, len*8.0 / ans);
    }
    return 0;
}

(2)利用有限队列

#include <stdio.h>
#include <queue>
#include <string.h>
#include <memory.h>
#include <vector>
#include <functional>
using namespace std;

char str[1005];

int main()
{
    //freopen("in.txt", "r", stdin);
    int num[27];
    while (scanf("%s", str)!=EOF && strcmp(str, "END")) {
        memset(num, 0, sizeof(num));
        int len = strlen(str);
        for (int i = 0; i < len; ++i){
            if (str[i] == '_')num[26]++;
            else num[str[i] - 'A']++;
        }
        priority_queue<int, vector<int>, greater<int> >pq;
        for (int i = 0; i < 27; ++i){
            if (num[i])pq.push(num[i]);
        }
        int ans = 0;
        while (pq.size()>1){
            int x = pq.top(); pq.pop();
            int y = pq.top(); pq.pop();
            ans += (x + y);
            pq.push(x + y);
        }
        if (ans == 0)ans = len;//如果只有一个元素
        printf("%d %d %.1lf\n", len * 8, ans, len*8.0 / ans);
    }
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值