hdu1053 哈弗曼编码
来源:互联网 发布:装饰公司网络推广方案 编辑:程序博客网 时间:2024/05/23 01:28
题目链接 Entropy
只需要求编码长度,不要求输出编码结果,所以不需要建树
对AAAAABCD,如图
总的编码长度=len(B)+len(C)+len(D)+5*len(A)=3+3+2+5*1=13
两种写法,都是nlogn
(1)利用sort排序
#include<stdio.h>#include<memory.h>#include<string.h>#include<algorithm>using namespace std;char str[1005];int num[27];bool cmp(int a, int b){ return a > b;}int main(){ //freopen("in.txt", "r", stdin); while (scanf("%s", str) != EOF&&strcmp(str, "END")){ memset(num, 0, sizeof(num)); int len = strlen(str); for (int i = 0; i < len; ++i){ if (str[i] == '_')num[26]++; else num[str[i] - 'A']++; } sort(num, num + 27, cmp); int n = 26; while (!num[n])n--; int ans = 0; if (n == 0){ ans = num[0]; }//注意这里!! else for (int i = n; i >= 1; --i) { num[i - 1] += num[i]; ans += num[i - 1]; sort(num, num + i + 1, cmp); } printf("%d %d %.1f\n", len * 8, ans, len*8.0 / ans); } return 0;}
(2)利用有限队列
#include <stdio.h>#include <queue>#include <string.h>#include <memory.h>#include <vector>#include <functional>using namespace std;char str[1005];int main(){ //freopen("in.txt", "r", stdin); int num[27]; while (scanf("%s", str)!=EOF && strcmp(str, "END")) { memset(num, 0, sizeof(num)); int len = strlen(str); for (int i = 0; i < len; ++i){ if (str[i] == '_')num[26]++; else num[str[i] - 'A']++; } priority_queue<int, vector<int>, greater<int> >pq; for (int i = 0; i < 27; ++i){ if (num[i])pq.push(num[i]); } int ans = 0; while (pq.size()>1){ int x = pq.top(); pq.pop(); int y = pq.top(); pq.pop(); ans += (x + y); pq.push(x + y); } if (ans == 0)ans = len;//如果只有一个元素 printf("%d %d %.1lf\n", len * 8, ans, len*8.0 / ans); } return 0;}
0 0
- hdu1053 哈弗曼编码
- 【哈夫曼编码】HDU1053-Entropy
- HDU1053 哈夫曼编码
- ZOJ1117 POJ1521 HDU1053 Huffman编码
- hdu1053:Entropy 之霍夫曼编码
- HDU1053 Entropy(huffman编码)
- hdu1053
- hdu1053
- ZOJ1117 POJ1521 HDU1053 Entropy,哈夫曼编码问题
- HDU1053,POJ1521,ZOJ1117 Entropy 哈夫曼编码
- 【POJ1521】【HDU1053】Entropy 哈夫曼(Huffman)编码
- hdu1053 Entropy —— 赫夫曼编码
- HDU1053--哈夫曼树
- HDU1053 Entropy
- HDU1053--Entropy
- HDU1053-Entropy
- Entropy hdu1053 哈夫曼树
- Hdu1053 step5.2.8(哈夫曼树)
- Hbase 批量删除
- Unreal Engine 4 字符串转换
- Eclipse插件svn和TortoiseSvn版本对应关系
- brocade 300交换机密码忘记重置
- java cpu高达100%问题 排查
- hdu1053 哈弗曼编码
- nginx访问第三方服务之subrequest使用
- 在windows中安装matplotlib
- Java初学笔记
- Objective-C之Foundation框架
- Unreal engine 4 C++ 一些调试用的绘制函数
- Matlab函数句柄调用图像K均值分类
- 关于数据表的一些SQL语句
- 对于检索的总结