描述
以前,没有电话的时候,进行快速远距离通信的主要手段是电报,即将所需要传送的文字转化成由二进制的字符组成的字符串。例如,假设需传送的电文为‘A B A C C D A’,它只有四种字符,根据字符出现的概率赋予每个字符一个权值(即字符在电文中出现的个数),比如:
A:3
B:1
C:2
D:1
此时我们有一种编码叫做Huffman编码可以对上述电文进行压缩(没有这个技术,人家可要多少你好多Money了!),现在要你完成Huffman编码,求出最后的平均码长。
输入
输入数据有多组,第一行输入测试数据组数m。接下来的m行中,每行一个n值开头,代表电文中有多少种不同的字符,后面输入n个正整数,表示每个字符的权值。假设字符种数不超过100个(英文不够可以用中文嘛^_^)。
输出
输出每组电文经过Huffman编码之后的平均码长,结果保留小数点后3位。
样例输入
2
2 1 1
4 3 1 2 1
样例输出
1.000
2.250
用优先队列要比用树简单的多,只是优先队列是C++中的。至于树比较烦,也不会写,所以还是算了。
#include<stdio.h>
#include<queue>
using namespace std;
struct node
{
int priority, i;
friend bool operator < (node a, node b)
{
if (a.priority != b.priority)//优先级,出现概率
return a.priority > b.priority;
return a.i > b.i;//次数
}
}p, a, b;
int main()
{
int t, n, i = 0, j = 0;
scanf ("%d", &t);
while (t--)
{
priority_queue <node> q;
scanf ("%d", &n);
for (i = 0; i < n; i++)
{
scanf ("%d", &p.priority);
p.i = 1;
q.push(p);
}
double sum = 0;
for (i = 0; i < n-1; i++)
{
a = q.top(); q.pop();
b = q.top(); q.pop();
p.priority = a.priority + b.priority;
p.i = a.i + b.i;
q.push(p);
sum += p.i;
}
printf ("%.3f\n", (double)sum/n);
}
return 0;
}
如果是求真正 的码长的话,代码实际上也没什么改动,只是数据统计的不是次数,而是出现的概率。除数也不是n,而是这n个数据的总和
#include<stdio.h>
#include<queue>
using namespace std;
struct node
{
int priority, i;
friend bool operator < (node a, node b)
{
if (a.priority != b.priority)//优先级
return a.priority > b.priority;
return a.i > b.i;//次数
}
}p, a, b;
int main()
{
int t, n, i = 0, j = 0;
scanf ("%d", &t);
while (t--)
{
priority_queue <node> q;
scanf ("%d", &n);
double res = 0;
for (i = 0; i < n; i++)
{
scanf ("%d", &p.priority);
res += p.priority;
p.i = 1;
q.push(p);
}
double sum = 0;
for (i = 0; i < n-1; i++)
{
a = q.top(); q.pop();
b = q.top(); q.pop();
p.priority = a.priority + b.priority;
p.i = a.i + b.i;
q.push(p);
sum += p.priority;
}
printf ("%.3f\n", (double)sum/res);
}
return 0;
}