题目:
http://acm.hdu.edu.cn/showproblem.php?pid=1053
霍夫曼编码的题目,要注意n==1时的特殊情况。
#include<stdio.h>
#include<iostream>
using namespace std;
const int inf = 1000000;
typedef struct hufcode{
int weight;
int parent;
int depth;
int lson;
int rson;
void set(){parent = -1;depth= 0;lson = -1;rson= -1;}
}hc;
hc *node;
int hash[30];
char str[100];
int build(int n){
int maxn = 2*n - 1;
int min1,min2,s1,s2;
for(inti = 0;i <n;i++)
node[i].set();
int j = 0;
for (int i = 0; i < 27; i++)
if(hash[i])
node[j++].weight = hash[i];
s1 = 0;
for(inti = 0;i <n-1;i++){
min1 = min2 = inf;
for(intj = 0;j <i+n;j++){
if(node[j].parent == -1 && min1> node[j].weight){
s2 = s1;
min2 = min1;
min1 = node[j].weight;
s1 = j;
}
else if(node[j].parent == -1 && min2> node[j].weight){
min2 = node[j].weight;
s2 = j;
}
}
node[i+n].weight = node[s1].weight + node[s2].weight;
node[i+n].parent = -1;
node[i+n].lson = s1;
node[i+n].rson = s2;
node[s1].parent = n+i;
node[s2].parent = n+i;
}
return maxn - 1;
}
void getdepth(int root,int depth){
if(node[root].lson == -1 &&node[root].rson == -1)
node[root].depth = depth;
else if(node[root].lson == -1)
getdepth(node[root].rson, depth+1);
else if(node[root].rson == -1)
getdepth(node[root].lson, depth+1);
else{
getdepth(node[root].lson, depth+1);
getdepth(node[root].rson, depth+1);
}
}
int main(){
int root,result;
node =(hufcode*)calloc(60,sizeof(hufcode));
while(scanf("%s",str)&&strcmp(str,"END")){
memset(hash, 0, sizeof(hash));
int len =(int)strlen(str);
for(inti = 0 ;i <len;i++)
if(str[i] == '_')
hash[26]++;
else
hash[str[i]-'A']++;
//for(int i = 0;i< 30;i++)
// printf("%d ",hash[i]);
int n =0;
for(inti = 0;i <27;i++)
if(hash[i])
n++;
if(n==1){
printf("%d %d 8.0\n",len*8,len);
continue;
}
root = build(n);
getdepth(root, 0);
int j =0;
result = 0;
for(int i = 0; i < 27; i++)
if(hash[i]){
//printf("%d %d\n",node[j].depth,hash[i]);
result += node[j++].depth*hash[i];
}
printf("%d %d%.1lf\n",len*8,result,(double)(len*8)/result);
}
free(node);
return 0;
}