hdu 1053 Entropy

來源:互聯網
上載者:User

連結:點擊開啟連結

對輸入字串【長度不知,僅含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;    }    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.