//第九章第14題;
//假設十個符號爲ABCDEFGHIJ,權值爲8,21,37,24,6,18,23,41,56,14;
//輸入權值:8回車;
//輸入數據:A(不用回車);
//輸入十個權值和數據後,輸出爲:A 11001 ;B 1011 ;C 101 ;D 100 ;E 01001 ;(E權值最小編碼最長)
//F 0011;G 000 ;H 111
//I 10 ;(I權值最大,編碼最短)J 0001;
//由於不知道編碼是否正確,因此不能保證本程序的正確性,但是從編碼輸出來看,
//滿足了權值最大,編碼最長,權值最小,編碼最短的條件;
#include "stdio.h"
#include "conio.h"
typedef char datatype;
#define n 10 //葉子數;
#define m 2*n-1 //結點總數;
typedef struct
{
char bits[n];
int start;
datatype data;
}codetype;//編碼數組的數據結構;
codetype code[n];
typedef struct
{
float weight;
datatype data;
int lchild,rchild,parent;
}hufmtree;
hufmtree tree[m]; //哈夫曼樹數據結構;
void printHuffman(hufmtree tree[])
{
for(int i=0;i<m;i++)
{
printf("%c %f/n",tree[i].data,tree[i].weight);
}
} //打印哈夫曼樹的函數;
void printHuffmancode(codetype code[])
{
for(int i=0;i<n;i++)
{
printf("%c/n",code[i].data);
for(int j=n-1;j>=code[i].start;j--)
{
printf("%c",code[i].bits[j]);
}
printf("/n");
}
} //打印哈夫曼樹編碼的函數
void humffman(hufmtree tree[])
{
printf("開始建立哈夫曼樹.../n");
int i,j;
int p1,p2;
char ch;
float small1,small2,f;
for(i=0;i<m;i++)
{
tree[i].parent=0;
tree[i].lchild=0;
tree[i].rchild=0;
tree[i].weight=0.0;
tree[i].data='0';
}
for(i=0;i<n;i++)
{
printf("輸入權值:");
scanf("%f",&f);
tree[i].weight=f;
printf("輸入數據:");
ch=getche();
printf("/n");
tree[i].data=ch;
}
printHuffman(tree);
printf("創建ing.../n");
for(i=n;i<m;i++)
{
p1=p2=0;
small1=small2=999999.0;
for(j=0;j<=i-1;j++)
if(tree[j].parent==0)
if(tree[j].weight<small1)
{
small2=small1;
small1=tree[j].weight;
p2=p1;
p1=j;
}
else if(tree[j].weight<small2)
{
small2=tree[j].weight;
p2=j;
}
tree[p1].parent=i;
tree[p2].parent=i;
tree[i].lchild=p1;
tree[i].rchild=p2;
tree[i].weight=tree[p1].weight+tree[p2].weight;
}
printHuffman(tree);
printf("創建完畢.../n");
} //創建哈夫曼樹;
void huffmancode(codetype code[],hufmtree tree[])
{
printf("編碼開始.../n");
int i,c,p;
codetype cd;
for(i=0;i<n;i++)
{
cd.start=n;
c=i;
p=tree[c].parent;
cd.data=tree[c].data;
while(p!=0)
{
cd.start--;
if(tree[p].lchild==c)
cd.bits[cd.start]='0';
else
cd.bits[cd.start]='1';
c=p;
p=tree[c].parent;
}
code[i]=cd;
}
printHuffmancode(code);
printf("編碼完成.../n");
} //創建哈夫曼樹編碼函數;
int main()
{
humffman(tree);
huffmancode(code,tree);
return 0;
} //main函數主要調用了兩個主要的哈夫曼樹創建與編碼函數,其中tree和code是全局變量的數組;