霍夫曼编码,用优先队列解决,注意只有一种字符的情况
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAX 1000000
using namespace std;
int map[100],length[100];
struct node
{
char s[50];
int all,sum;
bool operator <(node other)
{
return sum<other.sum;
}
}nod[50];
int main()
{
int i,j,t,len,front,all;
char input[MAX];
while(scanf("%s",input)&&strcmp(input,"END"))
{
memset(map,0,100*4);
memset(length,0,100*4);
all=0;
len=strlen(input);
for(i=0;i<len;i++)
map[input[i]]++;
for(i=0,j=0;i<=100;i++)
{
if(map[i]!=0)
{
nod[j].s[0]=i;
nod[j].all=1;
nod[j].sum=map[i];
j++;
}
}
front=0;
while(front<=j-2)
{
sort(nod+front,nod+j);
for(i=0;i<nod[front].all;i++)
length[nod[front].s[i]]++;
for(i=0;i<nod[front+1].all;i++)
length[nod[front+1].s[i]]++;
for(i=nod[front+1].all,t=0;i<nod[front+1].all+nod[front].all;i++,t++)
nod[front+1].s[i]=nod[front].s[t];
nod[front+1].sum+=nod[front].sum;
nod[front+1].all+=nod[front].all;
front++;
}
for(i=0;i<100;i++)
all+=map[i]*length[i];
if(all==0)
all=len;
printf("%d %d %.1lf\n",len*8,all,(double)(len*8)/(double)all);
}
return 0;
}