#include<stdio.h>
#define来自MAX30
#defineinf100000000
typedefcha胡解优频达系述周rvalType;
typedefintwghType;
structHFMnode
{
valTypedata;
wghTypeweight;
intparent;
intlchild;
intrchild;
};
struct笑便史曾用做会台说HFMcode
{
charcode[MAX];
intstart;
};
voidcreateHFMtree(HFMnode*node,intn)
{
inti,m1,m2,l,r;
for(i=n+1;i<=2*n-1;i++)
{
m1=m2=inf;
l=r=0;
intk;
for(k=1;k<=i-1步冷品亮省专车核;k++)
if(node[k].parent==0)
{
i360问答f(node[k].weight<m1)
{
m2=m1;
r=l;
m1=no多皇够定血伟女约位积令de[k].weight;
l=k;
}
elseif(node[k].weight<m2)
{
m2=node[k].weight;
r=k;
}
}
node[i].weight=no财道温检越陆苏正英de[l].weight+node[r].weight;
node[i].l坏积担望川算扬稳鲜甲临child=l;
node过的运胶必演未[i].rchild=r;
node[l].par茶固取何美请ent=i;
node[r].parent=i;
}
}
voidcreate查又距HFMcode(HFMn济斯沿套雨阶团家持概编ode*node,HFMcode*hco陈滑生亮杀吃蛋值算杂棉de,intn)
{
inti;
for(i=1;i<=n;i++)
{
HFMcoded;
d.start=n;
intnum=i;
intfather=node[num].parent;
wh红试喜ile(father!=0按派过江民士育条陈运)
{
if(node育训运威二面犯球民形[father].lchild==num)
d.code[d.start--]='0';
elsed.code[d.start--]='1';
num=father;
father=node[num].parent;
}
hcode[i]=d;
}
}
voidprintHFMcode(HFMnode*no反露伤限送甲州孙米与合de,HFMcode*hcode,intn)
{
inti;
for(i=1;i<=n州动女;i++)
{
printf("%c:",node[i].dat孙与错营烟难a);
for(in金tk=hcode[i].start+1;k<=n;k++)
putchar(hcode[i].code[k]);
puts("");
}
}
voidmain()
{
HFMnodenode[2*MAX];HFMcodehcd[MAX];
intn;
scanf("%d\n",&n);
for(inti=1;i<=n;i++){
printf("输入第%d个节点的值\n",i);
scanf("%c",&node[i].data);
printf("输入它的权重\n");
scanf("%d\n",&node[i].weight);
}
for(inti=1;i<=2*n-1;i++)
node[i].parent=node[i].lchild=node[i].rchild=0;
createHFMtree(node,n);
createHFMcode(node,hcd,n);
printHFMcode(node,hcd,n);
}
参考资料:http://blog.csdn.net/heyongluoyao8/article/details/6925209
输入文件格式例:
26
A7
B2
C2
D3
E11
F2
G2
H6
I6
J1
K1
L4
M3
N7
O9
P2
Q1
R6
S6
T8
U4
V1
W2
X1
Y2
Z1
标签:哈夫曼,树及,编码