/**
*2018.09.17 16:09
*赫夫曼编码
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
typedef struct HuffmanTree {
int weight;
int parent, lchild, rchild;
}HuffmanTree;
char** huffmanCoding(int *w, int n);
void getMins(HuffmanTree *tree, int rear, int *min1, int *min2);
int main(void) {
int w[] = {1000, 5000,2, 1, 3, 1, 8, 9, 66 , 365 ,987};
char **hc = huffmanCoding(w, sizeof(w)/sizeof(int));
for (int i = 0; i < sizeof(w) / sizeof(int); ++i)
puts(hc[i]);
free(hc);
putchar('\n');
system("pause");
return 0;
}
char** huffmanCoding(int *w, int n){
int s = 2 * n - 1;
HuffmanTree *ht = (HuffmanTree *)malloc(s * sizeof(HuffmanTree));
int i = 0;
for (i; i < n; ++i, ++w)
ht[i] = (HuffmanTree) {*w, -1, -1, -1};
for (i; i < s;++i)
ht[i] = (HuffmanTree) { -1, -1, -1, -1 };
int min1, min2;
for (i = n; i < s; ++i) {
getMins(ht, i, &min1, &min2);
ht[i].lchild = min1;
ht[i].rchild = min2;
ht[i].weight = ht[min1].weight + ht[min2].weight;
ht[min1].parent = i;
ht[min2].parent = i;
}
char **huffmanCode = (char **)malloc(n * sizeof(char *));
char *temp = (char *)malloc(n * sizeof(char));
temp[n - 1] = '\0';
int c, f, start;
for (i = 0; i < n; ++i) {
start = n - 1;
for (c = i, f = ht[c].parent; -1 != f; c = f, f = ht[f].parent) {
if (ht[f].lchild == c)
temp[--start] = '0';
else temp[--start] = '1';
}
huffmanCode[i] =(char *)malloc((n - start) - sizeof(char));
strcpy(huffmanCode[i], &temp[start]);
}
free(ht);
free(temp);
return huffmanCode;
}
void getMins(HuffmanTree *ht, int rear, int *min1, int *min2) {
int i = 0;
*min1 = *min2 = -1;
for (i; i < rear; ++i) {
if (-1 != *min1 && -1 != *min2)
break;
if (-1 == ht[i].parent)
if (-1 == *min1)
*min1 = i;
else *min2 = i;
}
for (i; i < rear; ++i) {
if (-1 == ht[i].parent && (ht[i].weight < ht[*min1].weight || ht[i].weight < ht[*min2].weight)) {
if (ht[*min1].weight < ht[*min2].weight)
*min2 = i;
else *min1 = i;
}
}
}
赫夫曼编码
最新推荐文章于 2024-07-26 10:34:47 发布