- 注册时间
- 2004-10-13
- 最后登录
- 2019-5-15
⑧专业
*永恒国度*
- 积分
- 14145

|
程序如下:- #include<stdio.h>
- #define MaxSize 50
- typedef struct
- {
- char data; //結點值
- int weight;//權重
- int parent;//父結點
- int left; //左結點
- int right; //右結點
- }huffnode;
- typedef struct
- {
- char cd[MaxSize];
- int start;
- }huffcode;
- void creahuffman(huffnode ht[],int n) // 構造哈夫曼樹
- {
- int i,k,l,r,m1,m2;
- for(i=0;i<2*n-1;i++)
- ht[i].parent=ht[i].left=ht[i].right=0;
- for(i=n;i<2*n-1;i++)
- {
- m1=m2=32767; //l,r為最小權重的兩個結點位置
- l=r=0;
- for(k=0;k<i-1;k++)
- if(ht[k].parent==0)
- if(ht[k].weight<m1)
- {
- m2=m1;r=l;
- m1=ht[k].weight;
- l=k;
- }
- else if(ht[k].weight<m2)
- {
- m2=ht[k].weight;
- r=k;
- }
- ht[l].parent=i;ht[r].parent=i;
- ht[i].weight=ht[l].weight+ht[r].weight;
- ht[i].left=l;ht[i].right=r;
- }
- }
- void creahfcode(huffnode ht[],huffcode hcd[],int n) //求哈夫曼編碼
- {
- int i,f,c;
- huffcode d;
- for(i=0;i<n;i++)
- {
- d.start=n+1;c=i;
- f=ht[i].parent;
- while(f!=0)
- {
- if(ht[f].left==c)
- d.cd[--d.start]='0';
- else
- d.cd[--d.start]='1';
- c=f;f=ht[f].parent;
- }
- hcd[i]=d;
- }
- }
- void disphuffman(huffnode ht[],huffcode hcd[],int n) //輸出哈夫曼編碼
- {
- int i,k;
- printf("輸出哈夫曼編碼:\n");
- for(i=0;i<n;i++)
- {
- printf("%c:",ht[i].data);
- for(k=hcd[i].start;k<=n;k++)
- printf("%c",hcd[i].cd[k]);
- printf("\n");
- }
- }
- void main()
- {
- int n=6;
- huffnode ht[2*MaxSize];
- huffcode hcd[MaxSize];
- ht[0].data='a'; ht[1].data='b';
- ht[2].data='c'; ht[3].data='d';
- ht[4].data='e'; ht[5].data='f';
- ht[0].weight=10; ht[1].weight=2;
- ht[2].weight=6; ht[3].weight=4;
- ht[4].weight=3; ht[5].weight=1;
- creahuffman(ht,n);
- creahfcode(ht,hcd,n);
- disphuffman(ht,hcd,n);
- }
复制代码
牠是結點在左子樹上編碼就為0,在右子樹上就為1。
大蝦們能詳細解釋下嗎?我實在是不太理解是怎麼實現的。 |
|