連結:點擊開啟連結
對輸入字串【長度不知,僅含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; }