博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
哈夫曼编码
阅读量:4134 次
发布时间:2019-05-25

本文共 2457 字,大约阅读时间需要 8 分钟。

//哈夫曼树构造原则: 权值小的在前,相等的单节点在前;#include "stdafx.h"#include 
#include
#include
typedef struct{ unsigned int weight; unsigned int parent,lchild,rchild;}HTNode,*HuffmanTree; typedef char **HuffmanCode;void Select(HuffmanTree &HT, int n, int &s1, int &s2){ //在HT[1..n]中选择parent为0且weight最小的两个结点,// 其序号分别为s1和s2。 int i; s1=-1;s2=-1; for(i=1; i<=n; i++) if(HT[i].parent == 0) { if(s1 == -1) s1 = i; else if(HT[i].weight < HT[s1].weight) { s2 = s1; s1 = i; } else if(s2 == -1 || HT[i].weight < HT[s2].weight) s2 = i; }}void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n){ // 并求出n个字符的哈夫曼编码HC int i, m, s1, s2, start; char *cd; unsigned int c, f; if (n<=1) return; m = 2 * n - 1; HT = (HuffmanTree)malloc((m+1) * sizeof(HTNode)); // 0号单元未用 for (i=1; i<=n; i++) { //初始化 HT[i].weight=w[i-1]; HT[i].parent=0; HT[i].lchild=0; HT[i].rchild=0; } for (i=n+1; i<=m; i++) { //初始化 HT[i].weight=0; HT[i].parent=0; HT[i].lchild=0; HT[i].rchild=0; } for (i=n+1; i<=m; i++) { // 建哈夫曼树 // 在HT[1..i-1]中选择parent为0且weight最小的两个结点, // 其序号分别为s1和s2。 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 = (char *)malloc(n*sizeof(char)); // 分配求编码的工作空间 cd[n-1] = '\0'; // 编码结束符。 for (i=1; i<=n; ++i) { // 逐个字符求哈夫曼编码 start = n-1; // 编码结束符位置 for (c=i, f=HT[i].parent; f!=0; c=f, f=HT[f].parent) // 从叶子到根逆向求编码 if (HT[f].lchild==c) cd[--start] = '0'; else cd[--start] = '1'; HC[i] = (char *)malloc((n-start)*sizeof(char)); // 为第i个字符编码分配空间 strcpy(HC[i], &cd[start]); // 从cd复制编码(串)到HC } free(cd); //释放工作空间} //HuffmanCodingint _tmain(int argc, _TCHAR* argv[]){ int i,n; int *w; HuffmanTree HT; HuffmanCode HC; printf("Node Number:"); scanf("%d",&n); //权值个数 w=(int *)malloc(n*sizeof(int)); printf("Input weights:"); for ( i=0;i

其中的select()函数亦可如下求解:

int min(HuffmanTree t,int i){    // 函数void select()调用    int j,flag;    unsigned int k=UINT_MAX; // 取k为不小于可能的值    for(j=1; j<=i; j++)        if(t[j].weight
s2) { j=s1; s1=s2; s2=j; }*/}

转载地址:http://fdsvi.baihongyu.com/

你可能感兴趣的文章
C++ sort
查看>>
C++ merge
查看>>
C++ set_union,set_intersection,set_difference
查看>>
第一章:左旋转字符串
查看>>
程序员编程艺术系列
查看>>
第二章:字符串是否包含问题
查看>>
简洁的heap代码
查看>>
最大团问题
查看>>
C++ make_heap,push_heap,pop_heap,sort_heap(以最大的K个数为例)
查看>>
第三章:寻找最小的k个数
查看>>
第三章续:O(n)复杂度算法
查看>>
Hash算法
查看>>
第三章再续:伴随数组求数组中给定下标区间内的第K小(大)元素
查看>>
第四章:一些字符串函数的实现
查看>>
第五章:寻找满足和为定值的两个或多个数
查看>>
动态规划6:最长递增子序列问题
查看>>
第六章:求解500万以内的亲和数
查看>>
第八章:虚函数笔记(虚函数碉堡了)
查看>>
动态规划7:最长公共子序列(LCS)
查看>>
第十二章:数的判断
查看>>