您的位置:首页 > 其它

赫夫曼编码(基于赫夫曼树的实现)

2017-08-15 11:41 246 查看
上一篇文章中我们探讨了赫夫曼树的基本原理和构造方式,而赫夫曼编码可以很有效地压缩数据(通常可以节约20%-90%的空间,具体压缩率依赖于数据的特性)。

名词:定长编码,边长编码,前缀码(装B用的)

定长编码:像ASCII编码

变长编码:单个编码的长度不一致,可以根据整体出现频率来调节

前缀码:所谓的前缀码,就是没有任何码字是其他码字的前缀

赫夫曼编码是基于贪心算法实现的(我以后的文章中会提到)

出现的次数越多,越靠前。例如下图的最高点132为次数(权重),则是第一位。



对于此代码,不作为重点,如果你是考研党,需能手写代码,如果只是为了提高编程能力,了解具体的思路即可,到真正用到的时候在翻阅相关具体代码。了解整体思路后,可以掌握大局。

C/C++实现:

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

#define N 10         // 带编码字符的个数,即树中叶结点的最大个数
#define M (2*N-1)    // 树中总的结点数目

class HTNode{        // 树中结点的结构
public:
unsigned int weight;
unsigned int parent,lchild,rchild;
};

class HTCode{
public:
char data;      // 待编码的字符
int weight;     // 字符的权值
char code
;   // 字符的编码
};

void Init(HTCode hc[], int *n){
// 初始化,读入待编码字符的个数n,从键盘输入n个字符和n个权值
int i;
printf("input n = ");
scanf("%d",&(*n));

printf("\ninput %d character\n",*n);

fflush(stdin);
for(i=1; i<=*n; ++i)
scanf("%c",&hc[i].data);

printf("\ninput %d weight\n",*n);

for(i=1; i<=*n; ++i)
scanf("%d",&(hc[i].weight) );
fflush(stdin);
}//

void Select(HTNode ht[], int k, int *s1, int *s2){
// ht[1...k]中选择parent为0,并且weight最小的两个结点,其序号由指针变量s1,s2指示
int i;

//找到s1
*s1 = i;

for(i=1; i<=k; ++i){
if(ht[i].parent==0 && ht[i].weight<ht[*s1].weight)
*s1 = i;
}

for(i=1; i<=k; ++i){
if(ht[i].parent==0 && i!=*s1)
break;
}

//找到s2
*s2 = i;

for(i=1; i<=k; ++i){
if(ht[i].parent==0 && i!=*s1 && ht[i].weight<ht[*s2].weight)
*s2 = i;
}
}

void HuffmanCoding(HTNode ht[],HTCode hc[],int n){
// 构造Huffman树ht,并求出n个字符的编码
char cd
;
int i,j,m,c,f,s1,s2,start;
m = 2*n-1;
//此for循环为建立森林
for(i=1; i<=m; ++i){
if(i <= n)
ht[i].weight = hc[i].weight;
ht[i].parent = ht[i].lchild = ht[i].rchild = 0;
}
//通过选取两个最小的值赋值给s1,s2。然后对ht数组进行操作,完成建立最优二叉树。
//其中ht[s1].parent是按照下标进行区分,不是存储的双亲的值,而是存储的双亲的位置。
for(i=n+1; i<=m; ++i){
Select(ht, i-1, &s1, &s2);
ht[s1].parent = i;
ht[s2].parent = i;
ht[i].lchild = s1;
ht[i].rchild = s2;
ht[i].weight = ht[s1].weight+ht[s2].weight;
}

cd[n-1] = '\0';

for(i=1; i<=n; ++i){
start = n-1;
for(c=i,f=ht[i].parent; f; c=f,f=ht[f].parent){
if(ht[f].lchild == c)
cd[--start] = '0';
else
cd[--start] = '1';
}
strcpy(hc[i].code, &cd[start]);
}
}

int main()
{
int i,m,n,w[N+1];
HTNode ht[M+1];
HTCode hc[N+1];
Init(hc, &n);     // 初始化
HuffmanCoding(ht,hc,n);   // 构造Huffman树,并形成字符的编码
for(i=1; i<=n; ++i)
printf("\n%c---%s",hc[i].data,hc[i].code);
printf("\n");

return 0;
}


C语言学习经验:

scanf(“%c”,地址);//所以以后做开发的时候,一定记住什么时候用地址,什么时候用地址对应的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: