hdu1053 Entropy(哈夫曼树)

复习了一天哈夫曼树。。。

去年只是学了哈夫曼的构建,但不懂这树的含义,今天想了好久,真的好厉害一棵树啊!

一个普通的字符串,竟然可以转变为带权值的树。我许久不能理解的是为什么字符出现次数可以用权值来表达,现在想这权值似乎就是为次数而建立的。。。有了很深的体会但脑子抽住了大哭,改天再好好谈谈对哈夫曼的看法吧。


本题由于不要求写出编码,所以用优先队列统计,权值小的权值优先加起来,相当于多了权值多的字节,出现次数少的所占字节越多,加的次数也就越多,正好符合哈夫曼的原理。

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;

const int N = 50;
const int INF = 1000000;

struct node
{
    int w;
    friend bool operator < (const node &a, const node &b)
    {
        return a.w > b.w;
    }
};

int main()
{
  //  freopen("in.txt", "r", stdin);
    char s[5000];
    int a[30];
    int ans;
    while(~scanf("%s", s))
    {
        ans = 0;
        if(!strcmp("END", s)) break; //比较字符串,相等输出的是0!
        int len = strlen(s);
        memset(a, 0, sizeof(a));
        for(int i = 0; i < len; i ++)
        {
            if(s[i] == '_') a[0] ++;
            else a[s[i] - 'A' + 1] ++;
        }
        priority_queue <node> q;
        for(int i = 0; i < 27; i ++)
        {
            node tmp;
            tmp.w = a[i];
            if(tmp.w) q.push(tmp);
        }
        if(q.size() == 1) ans = len;//只有一种字符,每个字符一个字节,共len个
        else
        {
            while(q.size() > 1)
            {
                node tmp2, tmp3, tmp0;
                tmp2 = q.top();
                q.pop();
                tmp3 = q.top();
                q.pop();
                tmp0.w = tmp2.w + tmp3.w;
                ans += tmp2.w + tmp3.w;
                q.push(tmp0);
            }
        }
        printf("%d %d %.1lf\n", len * 8, ans, (double)(len * 8) / ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值