hdu 1053 Entropy

来源:互联网 发布:杨振宁地位 知乎 编辑:程序博客网 时间:2024/05/21 07:57

链接:点击打开链接

对输入字符串【长度不知,仅含26个大写英文字母和一个空格表示符‘_’,共27种字符】,
统计每种字符出现频度,按哈夫曼编码原理给出最小的编码位数之和,得出与8位固定字长
编码的比率【保留一位小数】。
哈夫曼编码原理的理解及优先队列的运用<priority_queue>,引用头文件<queue>

注意一下字符串长度为1的情况就可以啦。。。

#include<iostream>#include<cstdio>#include<cstring>#include<queue>#include<vector>#include<algorithm>using namespace std;struct cmp{    bool operator()(int &a,int &b){        return a>b;        }    };int main(){    char str[1100];    int aa[27],sum,a,b;    priority_queue<int,vector<int>,cmp>Q;    int len,i;    while(~scanf("%s",str)){        while(!Q.empty())        Q.pop();        if(strcmp(str,"END")==0)        break;        len=strlen(str);        memset(aa,0,sizeof(aa));        for(i=0;i<len;i++)          if(str[i]=='_')           aa[26]++;           else           aa[str[i]-'A']++;        //for(i=0;i<27;i++)        //printf("%d ",aa[i]);          for(i=0;i<27;i++)         if(aa[i]!=0)         Q.push(aa[i]);         sum=0;         if(Q.size()==1)         sum=Q.top();         else{         while(Q.size()> 1){                a=Q.top();                Q.pop();                b=Q.top();                Q.pop();                sum+=(a+b);                Q.push(a+b);                }             }        len=len<<3;        printf("%d %d %.1lf\n",len,sum,len*1.0/sum);                  }        return 0;    }    


原创粉丝点击