hdu(1053)

题目: 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值