[Data structures]Huffman
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 20
#define INFINIT 65535
typedef struct _HTNode{
int weight;
int parent;
int left;
int right;
}HTNode;
void HuffmanCoding(HTNode **HT, char ***HC, int *w, int n)
{
int i;
int m;
int ma,mb,mt;
int sa,sb;
int j;
HTNode *p = NULL;
char **q = NULL;
char *cd = NULL;
int start;
/* Initial the huffman tree */
m = 2*n-1;
p = (HTNode *)malloc(sizeof(HTNode)*(m+1));
*HT = p;
for(i=1; i<=n; i++){
p[i].weight = w[i];
p[i].parent = p[i].left = p[i].right = 0;
}
for(;i<=m;i++){
p[i].weight = 0;
p[i].parent = p[i].left = p[i].right = 0;
}
/* Create the huffman tree */
for(i=n+1; i<=m; i++){
/* Select two minimal number from 1 to i-1 */
ma = mb = INFINIT;
for(j=1; j<=i-1; j++){
if(p[j].parent == 0){
if(mb > p[j].weight){
mb = p[j].weight;
sb = j;
}
if(ma > mb){
mt = ma;
ma = mb;
mb = mt;
mt = sa;
sa = sb;
sb = mt;
}
}
}
p[sa].parent = i;
p[sb].parent = i;
p[i].left = sa;
p[i].right = sb;
p[i].weight = p[sa].weight + p[sb].weight;
}
/* Encode every character from bottom to top.
* Of course you can also do it from top to bottom. */
q = (char **)malloc(sizeof(char *)*(n+1));
*HC = q;
cd = (char *)malloc(sizeof(char)*n);
for(i=1; i<=n; i++){
start = n-1;
cd[start] = 0;
for(j=i; p[j].parent; j=p[j].parent){
if(p[ p[j].parent ].left == j){
cd[--start] = '0';
}else{
cd[--start] = '1';
}
}
q[i] = (char *)malloc(sizeof(char)*(n-start));
strcpy(q[i], &cd[start]);
}
free(cd);
cd = NULL;
}
void main()
{
HTNode *HT;
char **HC;
int weight[] = {-1, 7, 5, 2, 4}; /* From 1 */
int data[] = {' ', 'a', 'b', 'c', 'd'};
int n = sizeof(data)/sizeof(int)-1;
int i,j;
printf("log.anycle.com\n\n");
printf("Original data:\n");
for(i=1; i<=n; i++){
printf(" %c(%2d)", data[i], weight[i]);
}
printf("\n");
printf("Huffman coding:\n");
HuffmanCoding(&HT, &HC, weight, n);
for(i=1; i<=n; i++){
printf(" %c(%s)", data[i], HC[i]);
}
printf("\n");
}
日历
最新微语
- 有的时候,会站在分叉路口,不知道向左还是右
2023-12-26 15:34
- 繁花乱开,鸟雀逐风。心自宁静,纷扰不闻。
2023-03-14 09:56
- 对于不可控的事,我们保持乐观,对于可控的事情,我们保持谨慎。
2023-02-09 11:03
- 小时候,
暑假意味着无忧无虑地玩很长一段时间,
节假意味着好吃好喝还有很多长期不见的小朋友来玩...
长大后,
这是女儿第一个暑假,
一个半月...
2022-07-11 08:54
- Watching the autumn leaves falling as you grow older together
2018-10-25 09:45
分类
最新评论
- Goonog
i get it now :) - 萧
@Fluzak:The web host... - Fluzak
Nice blog here! Also... - Albertarive
In my opinion you co... - ChesterHep
What does it plan? - ChesterHep
No, opposite. - mojoheadz
Everything is OK!... - Josephmaigh
I just want to say t... - ChesterHep
What good topic - AnthonyBub
Certainly, never it ...
发表评论: