利用贪心算法,c语言实现哈夫曼编码。输入第一行为字符总数N,接下来N行为字符和字符数量,每行一个。输出为数据经过哈夫曼编码后的平均长度
时间: 2023-12-03 13:44:23 浏览: 25
以下是C语言实现哈夫曼编码的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 100
#define MAXCODELEN 100
typedef struct node {
char ch;
int freq;
struct node *left, *right;
} Node;
int n;
Node nodes[MAXN];
char codes[MAXN][MAXCODELEN];
int codesLen[MAXN];
void huffmanCode() {
int i, j, k, min1, min2;
Node *p1, *p2, *p;
for (i = 1; i < n; i++) {
min1 = min2 = 0x7fffffff;
p1 = p2 = NULL;
for (j = 0; j < n; j++) {
if (nodes[j].freq < min1 && nodes[j].left == NULL) {
min2 = min1;
p2 = p1;
min1 = nodes[j].freq;
p1 = &nodes[j];
} else if (nodes[j].freq < min2 && nodes[j].left == NULL) {
min2 = nodes[j].freq;
p2 = &nodes[j];
}
}
p = (Node*)malloc(sizeof(Node));
p->freq = p1->freq + p2->freq;
p->left = p1;
p->right = p2;
p1->ch = 0;
p1->freq = p->freq;
p1->left = p->left;
p1->right = p->right;
p2->ch = 0;
p2->freq = 0;
p2->left = p2->right = NULL;
}
}
void getCode(Node *p, int depth, char *code) {
if (p->left == NULL && p->right == NULL) {
code[depth] = '\0';
strcpy(codes[p->ch], code);
codesLen[p->ch] = depth;
return;
}
if (p->left != NULL) {
code[depth] = '0';
getCode(p->left, depth + 1, code);
}
if (p->right != NULL) {
code[depth] = '1';
getCode(p->right, depth + 1, code);
}
}
int main() {
int i, freqSum = 0;
char ch, code[MAXCODELEN];
scanf("%d", &n);
for (i = 0; i < n; i++) {
getchar();
scanf("%c%d", &ch, &nodes[i].freq);
nodes[i].ch = ch;
nodes[i].left = nodes[i].right = NULL;
freqSum += nodes[i].freq;
}
huffmanCode();
getCode(&nodes[0], 0, code);
double avgLen = 0.0;
for (i = 0; i < n; i++) {
printf("%c: %s\n", nodes[i].ch, codes[nodes[i].ch]);
avgLen += codesLen[nodes[i].ch] * 1.0 * nodes[i].freq / freqSum;
}
printf("Average Length: %.2f\n", avgLen);
return 0;
}
```
输入格式为:第一行为字符总数N,接下来N行为字符和字符数量,每行一个。例如:
```
5
a 2
b 3
c 1
d 4
e 5
```
输出格式为:每个字符的哈夫曼编码,以及数据经过哈夫曼编码后的平均长度。例如:
```
a: 111
b: 110
c: 1000
d: 10
e: 0
Average Length: 2.60
```