【霍夫曼树】 poj 1521 Entropy

poj.org/problem?id=1521

注意只有特殊情况:只有一种字母

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
#include<map>

using namespace std;
const int maxm=1e7+2;
char str[maxm];
int main(){
    while(scanf("%s",str)&&strcmp(str,"END")){
        map<char,int> mp; 
        map<char,int>::iterator it;
        int len=strlen(str);
        for(int i=0;i<len;i++){
            mp[str[i]]++;
        } 
        priority_queue<int,vector<int>,greater<int> > Q;
        int cnt=0;
        for(it=mp.begin();it!=mp.end();it++){
            Q.push(it->second);
            cnt++;
        //    cout<<it->second<<endl;
        }    
        if(cnt==1){
            printf("%d %d %.1f\n",8*len,len,8.0);
            continue;
        }
        int ans=0;
        cnt--;
        while(cnt--){
            int x=Q.top();
            Q.pop();
            int y=Q.top();
            Q.pop();
            int z=x+y;
            ans+=z;
            Q.push(z);
        }
        double ratio=1.0*len*8/ans;
        printf("%d %d %.1f\n",8*len,ans,ratio);
    }
    return 0;
}

 

posted @ 2018-06-14 15:39  shulin15  阅读(141)  评论(0编辑  收藏  举报