#include "malloc.h"
#include "stdio.h"
#include "iostream.h"
typedef struct
{
unsigned int weight;
unsigned int parent,lchild,rchild;
}htnode,*huffmantree;
typedef char **huffmancode;
int min(huffmantree t,int i)
{
int j,flag;
unsigned int k=100;
for(j=1;j<=i;j++)
if(t[j].weight<k&&t[j].parent==0)
{
k=t[j].weight;
flag=j;
}
t[flag].parent=1;
return flag;
}
void select(huffmantree t,int i,int &s1,int &s2)
{
int j;
s1=min(t,i);
s2=min(t,i);
if(s1>s2)
{
j=s1;
s1=s2;
s2=j;
}
}
void huffmancoding(huffmantree &ht,huffmancode &hc,int *w,int n)
{
int m,i,s1,s2;
unsigned c,cdlen;
huffmantree p;
char *cd;
if(n<=1)
return;
m=2*n-1;
ht=(huffmantree)malloc((m+1)*sizeof(htnode));
for(p=ht+1,i=1;i<=n;++i,++p,++w)
{
(*p).weight=*w;
(*p).parent=0;
(*p).lchild=0;
(*p).rchild=0;
}
for(;i<=m;++i,++p)
(*p).parent=0;
for(i=n+1;i<=m;++i)
{
select(ht,i-1,s1,s2);
ht[s1].parent=ht[s2].parent=i;
ht[i].lchild=s1;
ht[i].rchild=s2;
ht[i].weight=ht[s1].weight+ht[s2].weight;
}
hc=(huffmancode)malloc((n+1)*sizeof(char*));
cd=(char*)malloc(n*sizeof(char));
c=m;
cdlen=0;
for(i=1;i<=m;++i)
ht[i].weight=0;
while(c)
{
if(ht[c].weight==0)
{
ht[c].weight=1;
if(ht[c].lchild!=0)
{
c=ht[c].lchild;
cd[cdlen++]='0';
}
else if(ht[c].rchild==0)
{
hc[c]=(char*)malloc((cdlen+1)*sizeof(char));
cd[cdlen]='\0';
strcpy(hc[c],cd);
}
}
else if(ht[c].weight==1)
{
ht[c].weight=2;
if(ht[c].rchild!=0)
{
c=ht[c].rchild;
cd[cdlen++]='1';
}
}
else
{
ht[c].weight=0;
c=ht[c].parent;
--cdlen;
}
}
free(cd);
}
int main()
{
huffmantree ht;
huffmancode hc;
int *w,n,i;
cout<<"请输入权值的个数(>1):";
cin>>n;
w=(int *)malloc(n*sizeof(int));
cout<<"请依次输入n个权值(整型):";
for(i=0;i<=n-1;i++)
cin>>*(w+i);
cout<<"对应赫夫曼编码为:\n";
huffmancoding(ht,hc,w,n);
for(i=1;i<=n;i++)
{
cout<<w[i-1]<<" ";
puts(hc[i]);
}
return 0;
}