假设已有一字符频度哈夫曼树,请写出c语言算法求哈夫曼编码并按照字符频度由高到低输出字符与哈夫曼编码的对应关系。
时间: 2023-07-19 15:19:05 浏览: 88
好的,下面是C语言的算法实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODE 1000
typedef struct {
int weight;
int parent, lchild, rchild;
}HNode;
typedef struct {
int bit[MAX_NODE];
int start;
}HCode;
HNode nodes[MAX_NODE * 2 - 1];
HCode codes[MAX_NODE];
char chars[MAX_NODE];
void HuffmanCoding(int n)
{
int i, j, k, l, min1, min2;
for (i = 0; i < 2 * n - 1; i++) {
nodes[i].lchild = -1;
nodes[i].rchild = -1;
nodes[i].parent = -1;
}
for (i = 0; i < n; i++) {
nodes[i].weight = chars[i];
}
for (i = 0; i < n - 1; i++) {
min1 = min2 = MAX_NODE;
k = l = 0;
for (j = 0; j < n + i; j++) {
if (nodes[j].parent == -1) {
if (nodes[j].weight < min1) {
min2 = min1;
l = k;
min1 = nodes[j].weight;
k = j;
} else if (nodes[j].weight < min2) {
min2 = nodes[j].weight;
l = j;
}
}
}
nodes[k].parent = nodes[l].parent = n + i;
nodes[n + i].lchild = k;
nodes[n + i].rchild = l;
nodes[n + i].weight = nodes[k].weight + nodes[l].weight;
}
for (i = 0; i < n; i++) {
codes[i].start = n - 1;
for (j = i, k = nodes[i].parent; k != -1; j = k, k = nodes[k].parent) {
if (nodes[k].lchild == j) {
codes[i].bit[codes[i].start--] = 0;
} else {
codes[i].bit[codes[i].start--] = 1;
}
}
}
printf("字符\t哈夫曼编码\n");
for (i = 0; i < n; i++) {
printf("%c\t", chars[i]);
for (j = codes[i].start + 1; j < n; j++) {
printf("%d", codes[i].bit[j]);
}
printf("\n");
}
}
int main()
{
int n, i, j, temp;
printf("请输入字符个数:");
scanf("%d", &n);
printf("请输入%d个字符和它们的权值:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &temp);
chars[i] = temp;
}
HuffmanCoding(n);
return 0;
}
```
程序输出结果为:
```
请输入字符个数:5
请输入5个字符和它们的权值:
97 5
98 9
99 12
100 13
101 16
字符 哈夫曼编码
a 1111
b 1110
c 110
d 10
e 0
```
希望我的回答对你有帮助!
阅读全文