您的位置:首页 > 其它

uvalive2088

2014-09-24 22:08 253 查看
题目的意思就是哈夫曼编码问题.

刚开始用建树时,一直出问题 .后来听别人说了一种不用建树的办法.

就是把每个节点的频数和所用编码长度保存下来.

每次两个节点相结合后,那么新节点相应的频数就是两个频数相加,而总的编码长度就为之前两个频数之和加上两个长度之和.

计算到最后一个时,它对应的频数便是我们要求的.

然后输出就好.

三个输出是如果每个字母都用八字节的编码长度(字符串长度乘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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: