UVALive - 2088 Entropy

10 篇文章 0 订阅

霍夫曼编码,用优先队列解决,注意只有一种字符的情况

#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAX 1000000
using namespace std;

int map[100],length[100];

struct node
{
    char s[50];
    int all,sum;
    bool operator <(node other)
    {
        return sum<other.sum;
    }
}nod[50];

int main()
{
    int i,j,t,len,front,all;
    char input[MAX];
    while(scanf("%s",input)&&strcmp(input,"END"))
    {
        memset(map,0,100*4);
        memset(length,0,100*4);
        all=0;
        len=strlen(input);
        for(i=0;i<len;i++)
            map[input[i]]++;
        for(i=0,j=0;i<=100;i++)
        {
            if(map[i]!=0)
            {
                nod[j].s[0]=i;
                nod[j].all=1;
                nod[j].sum=map[i];
                j++;
            }
        }
        front=0;
        while(front<=j-2)
        {
            sort(nod+front,nod+j);
            for(i=0;i<nod[front].all;i++)
                length[nod[front].s[i]]++;
            for(i=0;i<nod[front+1].all;i++)
                length[nod[front+1].s[i]]++;
            for(i=nod[front+1].all,t=0;i<nod[front+1].all+nod[front].all;i++,t++)
                nod[front+1].s[i]=nod[front].s[t];
            nod[front+1].sum+=nod[front].sum;
            nod[front+1].all+=nod[front].all;
            front++;
        }
        for(i=0;i<100;i++)
            all+=map[i]*length[i];
        if(all==0)
            all=len;
        printf("%d %d %.1lf\n",len*8,all,(double)(len*8)/(double)all);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值