哈弗曼編碼 哈弗曼樹

2021-09-25 02:31:32 字數 1737 閱讀 4045

哈弗曼編碼是依賴於字元使用頻率來建立的一種編碼,通過把使用頻率低的字元分配相對較多的01編碼,而使用頻率高的分配相對較低的01編碼,來建立最小的帶權路徑長度的樹,來最大化的獲得編碼儲存空間的一種編碼規則。這個樹稱為哈弗曼樹,也稱為最優二叉樹。

這樣可以確定每乙個字元的編碼不可能成為其他字元編碼的坐子串,也就是當讀到某乙個根節點時,就可以確定這個字元已經讀完了;下乙個字元的編碼要重新讀入。原因是經過這樣的編碼後,每個字元都位於哈弗曼樹的葉子節點(也就是到最後了),不可能再從這個葉子節點向下延伸(因為是葉子節點)。

#include

#include

#include

#include

#include

#include

#define inf 0x3f3f3f3f

using

namespace std;

typedef

struct

huffmantreenode;

typedef huffmantreenode *huffmantree;

typedef map<

char

, string> encode;

//找兩個weight最小的節點

void

findmin

(huffmantree t,

int n,

int&min1,

int&min2)

} t[min1]

.parent =-1

;for

(int i=

1; i<=n; i++)}

}//建立huffman樹

void

creadhuffmantree

(huffmantree *t,

int n)

printf

("enter the character and the weight:\n");

for(

int i=

1; i<=n; i++

)for

(int now=n+

1; now<=(2

*n-1

); now++)}

//前序遍歷輸出哈夫曼樹

void

printtree

(huffmantree t,

int root)

//哈夫曼編碼

void

huffmanencode

(huffmantree t,

int n, encode &encode)

printf

("%c\t\t%s\n"

, t[i]

.character, regulation+pos)

; string reg

(regulation + pos)

; encode[t[i]

.character]

= reg;}}

//哈夫曼解碼

void

huffmandecode

(encode encode,

char

*to_decode)}}

}int

main()

/*input

6a 45

b 13

c 12

d 16

e 9f 5

*/

哈弗曼樹與哈弗曼編碼(實現)

歷史背景 1951年,霍夫曼在mit攻讀博士學位,他和修讀資訊理論課程的同學得選擇是完成學期報告還是期末考試。導師robert fano出的學期報告題目是 查詢最有效的二進位制編碼。由於無法證明哪個已有編碼是最有效的,霍夫曼放棄對已有編碼的研究,轉向新的探索,最終發現了基於有序頻率二叉樹編碼的想法,...

哈弗曼編碼

include include include define my strmax 100 define infinity 1000000 typedef struct htnode,huffmantree 動態分配陣列儲存赫夫曼樹 typedef char huffmancode 動態分配陣列儲存赫...

哈弗曼編碼

include iostream include queue include vector include string using namespace std struct huffmantree bool operator const huffmantree t const vector h 相...