Код: Выделить всё
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define SIZE 256
struct SYM
{
unsigned char ch; //ascii
float freq; //symbol frequency
char code[SIZE]; //new huffman code
SYM *left; //left hand of tree
SYM *right; //right hand of tree
};
SYM* huffTree(SYM *syms[], int N) //array of SYM structs and size N
{
SYM *temp=(SYM*)malloc(sizeof(SYM));
temp->freq=syms[N-1]->freq+syms[N-2]->freq;
temp->code[0]=0;
temp->left=0;
temp->right=0;
temp->left=syms[N-2];
temp->right=syms[N-1];
if(N==2)
return temp;
else
{
for(int i=0;i<N;i++)
{
if(temp->freq>syms[i]->freq)
{
syms[N-1]=syms[i];
syms[i]=temp;
temp=syms[N-1];
}
}
return huffTree(syms, N-1);
}
}
void makeCodes(SYM *root)
{
if (root->left)
{
strcpy(root->left->code,root->code);
strcat(root->left->code,"0");
makeCodes(root->left);
}
if (root->right)
{
strcpy(root->right->code,root->code);
strcat(root->right->code,"1");
makeCodes(root->right);
}
}
int main()
{
int i=5;
SYM *syms[SIZE];
SYM arr[SIZE];
arr[0].ch='a';
arr[0].freq=0.4;
arr[1].ch='b';
arr[1].freq=0.3;
arr[2].ch='c';
arr[2].freq=0.1;
arr[3].ch='d';
arr[3].freq=0.1;
arr[4].ch='e';
arr[4].freq=0.1;
syms[0]=&arr[0];
syms[1]=&arr[1];
syms[2]=&arr[2];
syms[3]=&arr[3];
syms[4]=&arr[4];
SYM* root=huffTree(syms, i);
makeCodes(root);
}