Input 输入的第一行包含一个正整数n,表示共有n个字符需要编码。其中n不超过100。 第二行中有n个用空格隔开的正整数,分别表示n个字符的权值。 Output 共n行,每行一个字符串,表示对应字符的赫夫曼编码。c语言
时间: 2023-06-15 09:07:19 浏览: 188
以下是C语言的实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_N 100
struct node {
int weight;
int left;
int right;
int parent;
};
struct code {
int value;
char bits[MAX_N];
};
int compare(const void *a, const void *b) {
const struct node *node_a = (const struct node *)a;
const struct node *node_b = (const struct node *)b;
return node_a->weight - node_b->weight;
}
void huffman_encode(struct node *nodes, int n, struct code *codes) {
int i, j, parent, child;
char bit;
for (i = 0; i < n - 1; i++) {
parent = n + i;
child = nodes[i].weight < nodes[i+1].weight ? i : i+1;
nodes[child].parent = parent;
nodes[parent].weight = nodes[child].weight;
nodes[parent].left = child;
child = child == i ? i+1 : i;
nodes[child].parent = parent;
nodes[parent].weight += nodes[child].weight;
nodes[parent].right = child;
}
for (i = 0; i < n; i++) {
j = i;
bit = '0';
while (nodes[j].parent != -1) {
if (nodes[nodes[j].parent].left == j) {
codes[i].bits[strlen(codes[i].bits)] = bit;
} else {
codes[i].bits[strlen(codes[i].bits)] = bit == '0' ? '1' : '0';
}
j = nodes[j].parent;
bit = codes[i].bits[strlen(codes[i].bits)-1];
}
codes[i].value = i;
}
}
int main() {
int n, i;
struct node nodes[MAX_N*2-1];
struct code codes[MAX_N];
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &nodes[i].weight);
nodes[i].left = nodes[i].right = nodes[i].parent = -1;
}
qsort(nodes, n, sizeof(nodes[0]), compare);
huffman_encode(nodes, n, codes);
printf("Huffman codes:\n");
for (i = 0; i < n; i++) {
printf("%d: %s\n", codes[i].value, codes[i].bits);
}
return 0;
}
```
输入格式为:
```
n
w1 w2 ... wn
```
其中,wi 表示第 i 个字符的权值。
输出格式为:
```
Huffman codes:
v1: b1
v2: b2
...
vn: bn
```
其中,vi 表示第 i 个字符的值,bi 表示第 i 个字符的赫夫曼编码。
阅读全文