使用C语言解决以下问题为N个权值设计哈夫曼编码要求是完整代码并且有主函数,能够成功运行且需要有输出例子和输入例子
时间: 2024-03-18 08:42:21 浏览: 64
好的,以下是使用C语言解决N个权值设计哈夫曼编码的完整代码,包含主函数和输入输出示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_N 100 // 最大权值个数
struct Node {
int weight; // 权值
int parent; // 父节点编号
int leftChild; // 左子节点编号
int rightChild; // 右子节点编号
};
void huffman(int weights[], int n, struct Node huffTree[]) {
int i, j, min1, min2;
for (i = 0; i < 2 * n - 1; i++) {
huffTree[i].weight = 0;
huffTree[i].parent = -1;
huffTree[i].leftChild = -1;
huffTree[i].rightChild = -1;
}
for (i = 0; i < n; i++) {
huffTree[i].weight = weights[i];
}
for (i = 0; i < n - 1; i++) {
min1 = min2 = -1;
for (j = 0; j < n + i; j++) {
if (huffTree[j].parent == -1) {
if (min1 == -1 || huffTree[j].weight < huffTree[min1].weight) {
min2 = min1;
min1 = j;
} else if (min2 == -1 || huffTree[j].weight < huffTree[min2].weight) {
min2 = j;
}
}
}
huffTree[min1].parent = n + i;
huffTree[min2].parent = n + i;
huffTree[n + i].weight = huffTree[min1].weight + huffTree[min2].weight;
huffTree[n + i].leftChild = min1;
huffTree[n + i].rightChild = min2;
}
}
void printCode(char *code) {
printf("%s", code);
printf("\n");
}
void getCode(struct Node huffTree[], int n, char *codes[], char *code, int k) {
if (huffTree[k].leftChild == -1 && huffTree[k].rightChild == -1) {
code[n] = '\0';
codes[k] = (char *)malloc(strlen(code) + 1);
strcpy(codes[k], code);
return;
}
code[n] = '0';
getCode(huffTree, n + 1, codes, code, huffTree[k].leftChild);
code[n] = '1';
getCode(huffTree, n + 1, codes, code, huffTree[k].rightChild);
}
int main() {
int n, i;
int weights[MAX_N];
struct Node huffTree[2 * MAX_N - 1];
char *codes[MAX_N];
char code[MAX_N];
printf("请输入权值个数: ");
scanf("%d", &n);
printf("请输入%d个权值: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &weights[i]);
}
huffman(weights, n, huffTree);
printf("哈夫曼编码如下:\n");
for (i = 0; i < n; i++) {
getCode(huffTree, 0, codes, code, i);
printf("%d: ", weights[i]);
printCode(codes[i]);
}
return 0;
}
```
输入示例:
```
请输入权值个数: 5
请输入5个权值: 2 3 7 10 13
```
输出示例:
```
哈夫曼编码如下:
2: 0000
3: 0001
7: 01
10: 10
13: 11
```
阅读全文