您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树六:哈夫曼编码

2017-11-11 21:45 190 查看
数据结构实验之二叉树六:哈夫曼编码

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic

Problem Description

字符的编码方式有多种,除了大家熟悉的ASCII编码,哈夫曼编码(Huffman Coding)也是一种编码方式,它是可变字长编码。该方法完全依据字符出现概率来构造出平均长度最短的编码,称之为最优编码。哈夫曼编码常被用于数据文件压缩中,其压缩率通常在20%~90%之间。你的任务是对从键盘输入的一个字符串求出它的ASCII编码长度和哈夫曼编码长度的比值。

Input

输入数据有多组,每组数据一行,表示要编码的字符串。

Output

对应字符的ASCII编码长度la,huffman编码长度lh和la/lh的值(保留一位小数),数据之间以空格间隔。

Example Input

AAAAABCD

THE_CAT_IN_THE_HAT

Example Output

64 13 4.9

144 51 2.8

Hint

Author

xam

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int MAX = 300;
typedef struct node
{
int data;
struct node *next;
struct node *pre;
} d;
void push(d * &head, int em)
{
d *t = new d;
t->data = em;
t->next = NULL;
t->pre = NULL;
d *p;
if (head == NULL)
{
head = t;
return;
}
if (em >= head->data)
{
t->next = head;
head->pre = t;
head = t;
return;
}
p = head;
while (p != NULL)//p->next != NULL就不能到最后一个元素了
{
if (em >= p->data)
{
d *tp;
tp = p->pre;
tp->next = t;
t->pre = tp;
t->next = p;
p->pre = t;
break;
}
//当前数是最小数时
if (p->next == NULL)
{
p->next = t;
t->pre = p;
break;
}
p = p->next;
}
}

int main()
{
char str[MAX];
while (cin >> str)
{
int suma = 0, sumh = 0;
int len = strlen(str);
suma = len * 8;
int cth[MAX] = { 0 };
d *head;
head = NULL;
d *a, *b;
int ct = 0;
int i = 0;
while (i < len)
{
cth[str[i]]++;
i++;
}
i = 0;
while (i < MAX)
{
if (cth[i] != 0)
{
ct++;
push(head, cth[i]);
}
i++;
}
if (ct == 1)
{
sumh = head->data;
}
//计算次数
while (ct >= 2)
{
a = head;
while (a->ne
a30a
xt != NULL)//找到最后一个数
{
a = a->next;
}
b = a->pre;
int t;
t = b->data + a->data;
sumh += t;
//b = NULL;
b = b->pre;
if (b == NULL)//注意b是队列头
break;
b->next = NULL;
push(head, t);
ct--;
}
double aa = (double)suma / sumh;
printf("%d %d %.1lf\n", suma, sumh, aa);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: