贪心1003 POJ 1521-Entropy

典型HUFFMAN树的问题,用了STL的priority_queue
#include <iostream>  
#include <string>  
#include <queue>  
  
using namespace std;  
  
class node{  
public:  
    int key; //a,b,c...  
    int count;//频率  
    int p;//父亲结点  
    friend bool operator < (const node &a, const node &b)  
    {  
        if(b.count < a.count)  
            return true;  
        else  
            return false;  
    }  
};  
  
int value(char c)  
{  
    if(c=='_')  
        return 26;  
    else  
        return(c-'A');  
}  
  
int main()  
{  
    string str;  
    cin >> str;  
    while(str!="END")  
    {  
        node c[60];  
        for(int i=0;i<60;i++)  
        {  
            c[i].key=i;  
            c[i].count=0;  
        }  
        int length=str.length();  
        priority_queue<node> q;  
        for(int i=0;i<length;i++)  
        {  
            (c[value(str.at(i))]).count++;  
        }  
        for(int i=0;i<=26;i++)  
        {  
            if(c[i].count!=0)  
                q.push(c[i]);  
        }  
        if(q.size()==1)  
        {  
            printf("%d %d 8.0/n",8*length,length);  
        }  
        else  
        {  
            int n=27;  
            while(q.size()>1)  
            {  
                node s1=q.top();  
                q.pop();  
                node s2=q.top();  
                q.pop();  
                c[n].count=s1.count+s2.count;  
                c[s1.key].p=n;  
                c[s2.key].p=n;  
                q.push(c[n]);  
                n++;  
            }  
            int cnt=0;  
            for(int i=0;i<=26;i++)  
            {  
                if(c[i].count!=0)  
                {  
                    int height=1;  
                    int parent=c[i].p;  
                    while(parent!=n-1)  
                    {  
                        height++;  
                        parent=c[parent].p;  
                    }  
                    cnt+=height*c[i].count;  
                }  
            }  
            printf("%d %d %.1lf/n",8*length,cnt,(((double)(8*length))/((double)cnt)));  
        }  
        cin >> str;  
    }  
}  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值