uvalive2088
2014-09-24 22:08
253 查看
题目的意思就是哈夫曼编码问题.
刚开始用建树时,一直出问题 .后来听别人说了一种不用建树的办法.
就是把每个节点的频数和所用编码长度保存下来.
每次两个节点相结合后,那么新节点相应的频数就是两个频数相加,而总的编码长度就为之前两个频数之和加上两个长度之和.
计算到最后一个时,它对应的频数便是我们要求的.
然后输出就好.
三个输出是如果每个字母都用八字节的编码长度(字符串长度乘8) ,我们刚才求的编码长度. 和两个的比值.
AC代码:
刚开始用建树时,一直出问题 .后来听别人说了一种不用建树的办法.
就是把每个节点的频数和所用编码长度保存下来.
每次两个节点相结合后,那么新节点相应的频数就是两个频数相加,而总的编码长度就为之前两个频数之和加上两个长度之和.
计算到最后一个时,它对应的频数便是我们要求的.
然后输出就好.
三个输出是如果每个字母都用八字节的编码长度(字符串长度乘8) ,我们刚才求的编码长度. 和两个的比值.
AC代码:
#include <cstdio> #include <cstring> #include <string> #include <queue> #include <iostream> using namespace std; struct node { int num; int len; bool friend operator < (const node& a, const node& b) { return a.num > b.num; } }a[27]; string s; priority_queue<node> q; int main() { while (cin >> s && s != "END") { while (!q.empty()) q.pop(); memset(a, 0, sizeof(a)); int l = s.size(); for (int i = 0; i < l; i++) if (s[i] == '_') a[26].num++; else a[s[i] - 'A'].num++; for (int i = 0; i < 27; i++) if (a[i].num) q.push(a[i]); node tmp, t1, t2; if (q.size() == 1) { printf("%d %d 8.0\n", l * 8, l); continue; } while (q.size() != 1) { t1 = q.top(); q.pop(); t2 = q.top(); q.pop(); tmp.num = t1.num + t2.num; tmp.len = tmp.num + t1.len + t2.len; q.push(tmp); } printf("%d %d %.1lf\n", l * 8, tmp.len, double(l * 8) / tmp.len); } return 0; }
相关文章推荐
- uvalive 2088 - Entropy(huffman编码)
- uvalive 2088(哈夫曼树)
- uvalive 2088 - Entropy(huffman编码)
- UVALive - 2088 Entropy
- UVALIVE 2088 Entropy Huffman
- Huffman编码的不建树做法 UVALive 2088 Entropy
- UVALive 3882 And Then There Was One
- UVALive Problem 7456 Least Crucial Node——Regionals 2015 :: Asia - Taipei
- UVALive - 2963 Hypertransmission 暴力
- UVALive 7040 Color (容斥原理 + 组合数学递推公式 + 求逆元 + 基础数论)
- UVALive 2326 Moving Tables(贪心+不相交区间问题)
- UVALive 6534 Join two kingdoms 树的直径+期望
- UVALive 6918 And Or 数学二进制+枚举
- UVAlive 3708 Graveyard(最优化问题)
- 【UVALive】5135 Mining Your Own Business 点双连通+割顶
- UVALive 6425 Intercity(bfs)
- UVALive - 7270 Osu! Master
- UVALive 3644 X-Plosives
- UVAlive 6426 Count 读入二进制文件
- UVALive 5783 Everyone out of the Pool