hdu(1053)
来源:互联网 发布:fc2免费视频域名 编辑:程序博客网 时间:2024/04/28 05:00
题目: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
- hdu(1053)
- 哈夫曼编码(HDU 1053)
- hdu 1053
- hdu 1053
- HDU 1053
- 哈夫曼树 HDU 1053 HDU 2527
- hdu 2111(Saving HDU)
- hdu 2109(fighting hdu)
- HDU Saving HDU (贪心)
- Hdu 1053 Entropy查出错(修改)
- hdu 1053 Entropy(哈夫曼编码)
- HDU 1053 Entropy(huffman 编码)
- hdu 题目1053Entropy (赫夫曼树)
- HDU 1053 Entropy(哈夫曼编码)
- hdu 1050+hdu 1789+hdu 3177(贪心)
- 排位赛dp总结(HDU 2955,HDU 1864,HDU 1421)
- DFS基础 (HDU 1010、HDU 1016、HDU 1072)
- hdu 3715 hdu 1816 hdu 4115 (2-sat)
- code人心弦1101
- hdu 4268 Alice and Bob(贪心)
- zoj(3549)
- hdu(4422)
- hdu(4438)
- hdu(1053)
- hdu(1082)
- 对*nix中inode的几点理解
- hdu(1515)
- hdu(1257)
- hdu(1711)
- hdu(1213)
- hdu(1272)
- Pipeline(codeforces)