1. Huffman树不是唯一的,这是因为在选择具有最小权值的2个节点时会出现权值相等的情况。
编码效率是不是一样的?不一样,但相差不大。
如何选择最小的?
2. 一组数,找最小的两个,算法的复杂度是O(n + ceil(log(n)) - 2),使用堆排序。
3. Huffman编码算法用于压缩。
程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct ...{
unsigned int weight;
unsigned int parent;
unsigned int left;
unsigned int right;
}HNode;

typedef char **HCode;


void select(HNode *htree, int i, int &s1, int &s2)...{

for(int j = 1; j <= i; j++)...{

if(htree[j].parent != 0)...{
continue;

}else...{
s1 = j;
break;
}
}


for(j++; j <= i; j++)...{

if(htree[j].parent != 0)...{
continue;

}else...{
s2 = j;
break;
}
}


if(htree[s1].weight > htree[s2].weight)...{
int tmp = s2;
s2 = s1;
s1 = tmp;
}


for(j = 1; j <= i; j++)...{

if(htree[j].parent == 0)...{

if(htree[j].weight <= htree[s2].weight)...{

if(htree[j].weight < htree[s1].weight)...{
s2 = s1;
s1 = j;

}else...{

if(j != s1)...{
s2 = j;
}
}
}
}
}
}


void HuffmanCoding(HNode *htree, HCode &hcode, int *w, int n)...{

if(n <= 1)...{
return;
}
int m = 2 * n - 1;
int i = 0;
htree = (HNode *)malloc(sizeof(HNode) * (m + 1));
HNode *p = htree;

for(i = 1; i <= n; i++)...{
p++;
(*p).weight = w[i - 1];
(*p).parent = (*p).left = (*p).right = 0;
}

for(; i <= m; i++)...{
p++;
(*p).weight = (*p).parent = (*p).left = (*p).right = 0;
}
int s1 = 0, s2 = 0;

for(i = n + 1; i <= m; i++)...{
select(htree, i - 1, s1, s2);
htree[s1].parent = i;
htree[s2].parent = i;
htree[i].left = s1;
htree[i].right = s2;
htree[i].weight = htree[s1].weight + htree[s2].weight;
}
hcode = (HCode)malloc(sizeof(char *) * (n + 1));
char *ch = (char *)malloc(n * sizeof(char));
ch[n - 1] = '
执行结果为:
Huffman编码为:
a: 11111
b: 10
c: 1110
d: 000
e: 110
f: 01
g: 11110
h: 001
1111110000110
abde
Press any key to continue