#include <iostream>
using namespace std;
typedef struct
{
int weight;
int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char **HuffmanCode;
typedef char *EachHuffcode;
void Select(HuffmanTree HT,int length,int &s1,int &s2)
{
//s1 lowest,s2 lower
unsigned int min = 5000;
HuffmanTree p = HT;
int i;
for(i = 1, ++p; i <= length ; ++i,++p)
{
if(p->weight < min && p->parent == 0)
{
min = p->weight;
s1 = i;
}
}
min = 5000;
p = HT;
//Get the second less weight
for(i = 1, ++p; i <= length ; ++i,++p)
{
if(p->weight < min && p->parent == 0)
{
if( i == s1)//case s1,ignore
continue;
min = p->weight;
s2 = i;
}
}
}
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC, int *w,int n)
{
if(n <= 1)
return;
int m = 2 * n - 1;
HT = new HTNode[m + 1];//0 is not used
HuffmanTree p = HT;
int i;
for( i = 1, ++p; i <= n; ++i,++p,++w)
{
p->weight = *w;//NOte: never use this *p = {*w,0,0,0,0},because *p has already been declared
p->parent = p->lchild = p->rchild = 0;
}
for(; i <= m; ++i,++p)
p->weight = p->parent = p->lchild = p->rchild = 0;
int s1;
int s2;
for( i = n + 1; i <= m; ++i)
{
Select(HT,i-1,s1,s2);
HT[s1].parent = i ;
HT[s2].parent = i;
HT[i].lchild = s1;
HT[i].rchild = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
HC = new EachHuffcode[n+1];//0 is not used
char *cd = new char[n];
cd[n-1] = '/0';//the end of each char
int start;
for(int i = 1; i <= n ; ++i)
{//get each huff code for h[1] to h[n]
start = n -1;
for(int c = i, int f = HT[i].parent; f != 0; c = f ,f = HT[f].parent)
if(c == HT[f].lchild) cd[--start] = '0';
else cd[--start] = '1';
HC[i] = new char[n - start];//allocate memory for each HT
strcpy(HC[i],&cd[start]);
}
delete []cd;//don't forget release memory
}
int main(int argc, char* argv[])
{
HuffmanTree hftree = NULL;
HuffmanCode hfcode = NULL;
int weight[4] = {7,5,2,4};//four node's weight
HuffmanCoding(hftree,hfcode,weight,4);
EachHuffcode *p = hfcode;
++p;
for (int i = 0; i < 4; ++i,++p)
{
cout<<*p<<endl;//show each huffman code by each line
}
for(int i = 1; i <=4; ++i)
delete hfcode[i];//release memory
delete []hfcode;
delete []hftree;
return 0;
}