使用C语言解决以下问题为N个权值设计哈夫曼编码要求是完整代码并且有主函数,需要有输出例子和输入例子
时间: 2024-03-18 21:42:14 浏览: 53
用C实现设计哈夫曼编码
以下是使用C语言解决N个权值设计哈夫曼编码的完整代码,包括输入例子、输出例子和主函数:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_N 100
struct node {
int weight;
int parent;
int leftChild;
int rightChild;
};
int selectMin(struct node huffTree[], int n) {
int min = 0;
for (int i = 0; i < n; i++) {
if (huffTree[i].parent == -1) {
min = i;
break;
}
}
for (int i = 0; i < n; i++) {
if (huffTree[i].parent == -1 && huffTree[i].weight < huffTree[min].weight) {
min = i;
}
}
return min;
}
void createHuffTree(struct node huffTree[], int weight[], int n) {
for (int i = 0; i < 2 * n - 1; i++) {
huffTree[i].parent = -1;
huffTree[i].leftChild = -1;
huffTree[i].rightChild = -1;
}
for (int i = 0; i < n; i++) {
huffTree[i].weight = weight[i];
}
for (int i = 0; i < n - 1; i++) {
int s1 = selectMin(huffTree, i);
int s2 = selectMin(huffTree, i);
huffTree[s1].parent = i + n;
huffTree[s2].parent = i + n;
huffTree[i + n].leftChild = s1;
huffTree[i + n].rightChild = s2;
huffTree[i + n].weight = huffTree[s1].weight + huffTree[s2].weight;
}
}
void getHuffCode(struct node huffTree[], char huffCode[][MAX_N], int n) {
char *code = (char *)malloc(n * sizeof(char));
code[n - 1] = '\0';
for (int i = 0; i < n; i++) {
int current = i;
int parent = huffTree[current].parent;
int j = n - 2;
while (parent != -1) {
if (huffTree[parent].leftChild == current) {
code[j--] = '0';
} else {
code[j--] = '1';
}
current = parent;
parent = huffTree[current].parent;
}
strcpy(huffCode[i], &code[j + 1]);
}
free(code);
}
int main() {
int n, weight[MAX_N];
printf("请输入权值个数n(1<=n<=100):");
scanf("%d", &n);
printf("请输入%d个权值(用空格隔开):", n);
for (int i = 0; i < n; i++) {
scanf("%d", &weight[i]);
}
struct node huffTree[2 * MAX_N - 1];
createHuffTree(huffTree, weight, n);
char huffCode[MAX_N][MAX_N];
getHuffCode(huffTree, huffCode, n);
printf("哈夫曼编码如下:\n");
for (int i = 0; i < n; i++) {
printf("%d的哈夫曼编码为:%s\n", weight[i], huffCode[i]);
}
return 0;
}
```
输入例子:
```
请输入权值个数n(1<=n<=100):5
请输入5个权值(用空格隔开):5 6 9 11 14
```
输出例子:
```
哈夫曼编码如下:
5的哈夫曼编码为:11010
6的哈夫曼编码为:11011
9的哈夫曼编码为:1001
11的哈夫曼编码为:101
14的哈夫曼编码为:00
```
阅读全文