標籤:pre 定義 art type start 根據 get its main
qiqifanqi 原文:http://blog.csdn.net/qiqifanqi/article/details/6038822
#include<stdio.h>#define MAX 100#define MAXVALUE 500typedef struct{ int weight; int parent,lchild,rchild;}node; /*哈夫曼樹結點類型*/ /*-----------------------------以下部分定義哈夫曼編碼儲存結構-------------------------*/typedef struct{ int start; //存放起始位置 char bits[10+1]; //存放編碼位串 }codetype;typedef struct{ char symbol; //儲存字元 codetype code;}element;void getMinElementLocal(node t[] ,int num , int *minLocal1 , int *minLocal2) ;/*---------------------------------------------------------------------------------------------------*//*構建哈夫曼樹。n為構建哈夫曼樹的葉子結點個數,數組w儲存每個葉子的權值,數組t儲存構建好的哈夫曼樹*/void huffman(int n,int w[],node t[]){ int m = 0 ; int minLocal1 , minLocal2 ; int i = 0 ; node * nodes = NULL ; if(n == 0) return ; m = 2*n -1 ; for(i = 1 ; i <= n ; i ++){ t[i].weight = w[i] ; t[i].lchild = t[i].parent = t[i].rchild = -1 ; } for(; i <= m ; i ++){ t[i].weight = 0 ; t[i].lchild = t[i].parent = t[i].rchild = -1 ; } for(i = 1 ; i <= n-1 ; i ++){ minLocal1 = minLocal2 = -2 ; getMinElementLocal(t , n+i , &minLocal1 , &minLocal2) ; t[n+i].weight = t[minLocal1].weight + t[minLocal2].weight ; t[n+i].lchild = minLocal1 ; t[n+i].rchild = minLocal2 ; t[minLocal1].parent = n+i ; t[minLocal2].parent = n+i ; } }void getMinElementLocal(node t[] ,int num , int *minLocal1 , int *minLocal2){ int i = 0 ; int temp1 = MAXVALUE ; int temp2 = MAXVALUE ; *minLocal1 = *minLocal2 = 0 ; for(i = 1 ; i < num ; i ++){ if(t[i].weight <= temp1 && t[i].parent == -1){ temp1 = t[i].weight ; *minLocal1 = i ; } } for(i = 1 ; i < num ; i ++){ if(t[i].weight <= temp2 && t[i].parent == -1 && i != *minLocal1){ temp2 = t[i].weight ; *minLocal2 = i ; } }}/*---------------------------------------------------------------------------------------------------*//*根據哈夫曼樹,求哈夫曼編碼錶。tree儲存哈夫曼樹,table儲存哈夫曼編碼錶,n為哈夫曼樹葉子個數*/void sethufcode(node tree[],element table[],int n) { int i,j,s,f; /* 和f分別指示tree中孩子和雙親的位置*/ codetype c;/*時存放編碼 */ for(i=1;i<=n;i++)/*次求葉子tree[i]的編碼 */ { printf("%d:",tree[i].weight); c.start=n+1; s=i;/*葉子tree[i]開始上溯 */ while(tree[s].parent != -1)/*至上溯到樹根為止 */ { f=tree[s].parent ; c.bits[--c.start]= (s == tree[f].lchild)?‘0‘:‘1‘; s=f; } for(j=c.start ;j<n+1;j++) printf("%c",c.bits[j]); printf("/n"); table[i].code=c;/*時編碼複製到最終位置 */ } }/*---------------------------------------------------------------------------------------------------*/void main(){ node t[100]; int i,n,w[100]; element m[100]; printf("請輸入結點數:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("請輸入第%d個結點權重:", i); scanf("%d",&w[i]); } /*構造哈夫曼樹*/ huffman(n ,w , t) ; printf("序號 權重 雙親 左孩 右孩/n"); /*輸出哈夫曼樹*/ for(i=1;i<(2*n);i++) printf("%-5d%-5d%-5d%-5d%-5d/n",i,t[i].weight,t[i].parent,t[i].lchild,t[i].rchild); sethufcode(t,m,n); /*構造並輸出哈夫曼編碼錶*/ }
轉載:哈夫曼樹的構造和哈夫曼編碼(C++代碼實現)