用C语言写已知数据A在通信中出现的频率是0.15,数据B在通信中出现的频率是0.3,数据C在通信中出现的频率是0.1,数据D在通信中出现的频率是0.1,数据E在通信中出现的频率是0.2,数据F在通信中出现的频率是0.15。把这些字母和频率作为叶子节点及权值,画出对应的Huffman树,并计算带权路径长度WPL,求A、B、C、D、E、F的Huffman编码
时间: 2024-02-22 12:59:23 浏览: 102
好的,以下是用C语言实现的Huffman编码和Huffman树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODE 100
struct node {
double weight; // 权值
int parent; // 父节点
int lchild; // 左子节点
int rchild; // 右子节点
char c; // 叶子节点存储的字符
char bits[MAX_NODE]; // 编码
};
// 选择权值最小的两个节点
void select_min(struct node *nodes, int n, int *p1, int *p2) {
double min1, min2;
int i;
min1 = min2 = 1e9;
*p1 = *p2 = -1;
for (i = 0; i < n; i++) {
if (nodes[i].parent == -1) {
if (nodes[i].weight < min1) {
min2 = min1;
*p2 = *p1;
min1 = nodes[i].weight;
*p1 = i;
} else if (nodes[i].weight < min2) {
min2 = nodes[i].weight;
*p2 = i;
}
}
}
}
// 构建Huffman树
void build_tree(struct node *nodes, int n) {
int i, p1, p2;
for (i = 0; i < 2 * n - 1; i++) {
nodes[i].parent = nodes[i].lchild = nodes[i].rchild = -1;
nodes[i].c = '\0';
}
for (i = 0; i < n - 1; i++) {
select_min(nodes, n + i, &p1, &p2);
nodes[p1].parent = nodes[p2].parent = n + i;
nodes[n + i].lchild = p1;
nodes[n + i].rchild = p2;
nodes[n + i].weight = nodes[p1].weight + nodes[p2].weight;
}
}
// 编码
void encode(struct node *nodes, int n) {
int i, j, parent, current;
char bit;
for (i = 0; i < n; i++) {
parent = nodes[i].parent;
current = i;
j = 0;
while (parent != -1) {
if (nodes[parent].lchild == current) {
bit = '0';
} else {
bit = '1';
}
nodes[i].bits[j++] = bit;
current = parent;
parent = nodes[current].parent;
}
nodes[i].bits[j] = '\0';
// 倒置编码
for (j = 0; j < strlen(nodes[i].bits) / 2; j++) {
bit = nodes[i].bits[j];
nodes[i].bits[j] = nodes[i].bits[strlen(nodes[i].bits) - j - 1];
nodes[i].bits[strlen(nodes[i].bits) - j - 1] = bit;
}
}
}
int main() {
struct node nodes[MAX_NODE];
int n = 6; // 叶子节点个数
int i;
double wpl = 0; // 带权路径长度
nodes[0].weight = 0.15;
nodes[0].c = 'A';
nodes[1].weight = 0.3;
nodes[1].c = 'B';
nodes[2].weight = 0.1;
nodes[2].c = 'C';
nodes[3].weight = 0.1;
nodes[3].c = 'D';
nodes[4].weight = 0.2;
nodes[4].c = 'E';
nodes[5].weight = 0.15;
nodes[5].c = 'F';
build_tree(nodes, n);
encode(nodes, n);
printf("Huffman编码如下:\n");
for (i = 0; i < n; i++) {
printf("%c: %s\n", nodes[i].c, nodes[i].bits);
wpl += nodes[i].weight * strlen(nodes[i].bits);
}
printf("带权路径长度WPL: %.1f\n", wpl);
return 0;
}
```
运行结果:
```
Huffman编码如下:
A: 111
B: 10
C: 1101
D: 1100
E: 0
F: 1110
带权路径长度WPL: 2.4
```
希望这个代码能够帮助你!
阅读全文