典型的哈弗曼编码。借助优先队列,当输入只有一种符号的时候需要另作讨论
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct node{
friend bool operator<(const node a,const node b)
{
return a.w>b.w;
}
int w;
};
int main()
{
char b[10005];
int ans;
while(scanf("%s",b)&&strcmp(b,"END")!=0)
{
ans=0;
priority_queue<node>q;
int i;
int a[300];
memset(a,0,sizeof(a));
int len=strlen(b);
for(i=0;i<len;i++)
a[b[i]]++;
for(i=0;i<=256;i++)
{
if(a[i]>0)
{
node s;
s.w=a[i];
q.push(s);
}
}
int sum=0;
if(q.size()==1)
{
ans=len;
}
else
{
while(q.size()!=1)
{
int tmp;
node t,tmp1,tmp2;
tmp1=q.top();
q.pop();
tmp2=q.top();
q.pop();
tmp=tmp1.w+tmp2.w;
t.w=tmp;
sum+=tmp;
q.push(t);
}
ans=sum;
}
printf("%d %d %.1lf\n",len*8,ans,len*8.0/ans);
}
return 0;
}