给出文件中题目:给定五个字符a~f,它们的权值集W={2,3,4,7,8,9},试构造关于W的一棵哈夫曼树,求其带权路径长度WPL和各个字符的哈夫曼编码。的具体c语言代码
时间: 2024-12-29 11:35:32 浏览: 25
基于您的需求,以下是针对给定问题的具体C语言代码实现,用于构造哈夫曼树,求其带权路径长度WPL以及每个字符对应的哈夫曼编码:
### 定义数据结构
首先定义节点和哈夫曼编码的结构体:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct HTNode {
unsigned int weight;
unsigned int parent, lchild, rchild;
} HTNode, *HuffmanTree;
typedef struct {
unsigned char bit[10];
int start;
} HCode, *HCoding;
```
### 构造哈夫曼树
构造哈夫曼树的函数 `CreateHuffmanTree`:
```c
void CreateHuffmanTree(HuffmanTree *ht, int *w, int n) {
if(n <= 1)
return;
HuffmanTree huffman = (HuffmanTree)malloc((n*2+1)*sizeof(HTNode));
for(int i = 0; i <= n*2; ++i) {
huffman[i].parent = huffman[i].lchild = huffman[i].rchild = -1;
}
for(int i = 1; i <= n; ++i)
huffman[i].weight = w[i-1];
int m = 2*n - 1;
for(int i = n + 1; i <= m; ++i) {
int s1 = -1, s2 = -1, min1, min2;
for(int j = 1; j <= i - 1; ++j) {
if(huffman[j].weight > 0 && huffman[j].parent == -1) {
if(s1 == -1 || huffman[j].weight < min1) {
s2 = s1;
min2 = min1;
s1 = j;
min1 = huffman[j].weight;
} else if(s2 == -1 || huffman[j].weight < min2) {
s2 = j;
min2 = huffman[j].weight;
}
}
}
huffman[s1].parent = huffman[s2].parent = i;
huffman[s2].lchild = s2;
huffman[s1].rchild = s1;
huffman[i].weight = huffman[s1].weight + huffman[s2].weight;
}
*ht = huffman;
}
```
### 生成哈夫曼编码
生成哈夫曼编码的函数 `GenerateHuffmaanCodes`:
```c
void GenerateHuffmaanCodes(HuffmanTree ht, int n, HCoding cd) {
int start;
cd = (HCoding)malloc((n+1)*sizeof(HCode));
for(int i = 1; i <= n; ++i) {
start = 10; /* 从bit[1]开始存储,从第10位倒回至1位 */
for(int c = i, f = ht[i].parent; f != -1; c=f, f=ht[f].parent) {
if(ht[f].lchild == c)
cd[i].bit[--start] = '0';
else
cd[i].bit[--start] = '1';
}
cd[i].start = start;
}
}
```
### 打印哈夫曼编码
打印哈夫曼编码的函数 `PrintHuffmaanCodes`:
```c
void PrintHuffmaanCodes(HCoding cd, int *ch, int n) {
int WPL = 0;
printf("Huffman Coding: \n");
for(int i = 1; i <= n; ++i) {
printf("%c: ", ch[i-1]);
for(int j = cd[i].start; j <= 10; ++j) {
printf("%c", cd[i].bit[j]);
WPL += ('0' == cd[i].bit[j]) ? 0 : ht[i].weight;
}
printf("\n");
}
printf("Weighted Path Length (WPL): %d\n", WPL);
}
```
### 主函数
整合以上所有部分,形成完整程序:
```c
int main() {
int weights[] = {2, 3, 4, 7, 8, 9};
char chars[] = {'a', 'b', 'c', 'd', 'e', 'f'};
int n = sizeof(weights) / sizeof(int);
HuffmanTree ht = NULL;
HCoding hc = NULL;
CreateHuffmanTree(&ht, weights, n);
GenerateHuffmaanCodes(ht, n, hc);
PrintHuffmaanCodes(hc, chars, n);
free(ht);
free(hc);
return 0;
}
```
此程序段能够构造给定重量集下的哈夫曼树,并生成每个字符对应的编码及计算WPL。注意内存的合理分配与释放以保证没有内存泄漏的问题出现。
阅读全文