Huffman coding哈夫曼編碼

2021-07-11 10:23:50 字數 1202 閱讀 4101

description

in computer science and information theory, a huffman code is an optimal prefix code algorithm.

in this exercise, please use huffman coding to encode a given data.

you should output the number of bits, denoted as b(t), to encode the data:

b(t)=∑f(c)d

t(c),

where f(c) is the frequency of character c, and d

t(c) is be the depth of character c's leaf in the tree t.

input

the first line is the number of characters n.

the following n lines, each line gives the character c and its frequency f(c).

output

output a single number b(t).

題目解釋:對給出的節點構建哈夫曼樹

輸入:第一行表示有節點數n,後面n行表示n個節點,每乙個節點(也就是每一行)使用節點號和出現頻率來表示

輸出:b(t) = f(c)d(c)總和(f(c)表示節點c的頻率,d(c)表示節點c在哈弗曼樹中的深度)

#include #include #include using namespace std;

struct huffmannode

};typedef huffmannode *htnode;

struct cmp

};int main()

int bt = 0;

while(pq.size()>1)

cout << bt << endl;

}return 0;

}

後記:1.priority_queue能夠及時對節點進行排序,可以最快地獲得更新後的最小兩個節點,實現新的更新

**新手,歡迎各位大神提出寶貴的意見和建議

Huffman Coding 哈夫曼編碼

使用優先佇列實現,需要注意以下幾點 1.在使用priority queue時,內部需要儲存哈夫曼樹節點的指標,而不能是節點。因為構建哈夫曼樹時,需要把其左右指標指向孩子,而如果儲存的是節點,那麼孩子的位址是會改變的。同理節點應當使用new在記憶體中開闢,而不能使用vector,原因是vector在陣...

哈夫曼編碼 哈夫曼樹

1.定義 哈夫曼編碼主要用於資料壓縮。哈夫曼編碼是一種可變長編碼。該編碼將出現頻率高的字元,使用短編碼 將出現頻率低的字元,使用長編碼。變長編碼的主要問題是,必須實現非字首編碼,即在乙個字符集中,任何乙個字元的編碼都不是另乙個字元編碼的字首。如 0 10就是非字首編碼,而0 01不是非字首編碼。2....

哈夫曼樹 哈夫曼編碼

定義從a結點到b結點所經過的分支序列為從a結點到b結點的路徑 定義從a結點到b結點所進過的分支個數為從a結點到b結點的路徑長度 從二叉樹的根結點到二叉樹中所有結點的路徑長度紙盒為該二叉樹的路徑長度 huffman樹 帶權值路徑長度最小的擴充二叉樹應是權值大的外界點舉例根結點最近的擴充二叉樹,該樹即為...