哈弗曼編碼

2021-07-12 00:19:20 字數 1363 閱讀 2113

問題描述:給定字符集c和每個字元的頻率,求關於c的乙個最優字首碼。

演算法分析:構造最優字首碼的貪心演算法就是哈夫曼演算法(huffman)

二元字首編碼儲存:二叉樹結構,每個字元作為樹葉,對應這個字元的字首碼看作根到這片樹葉的一條路徑,每個結點通向左二子的邊記作0,通向右兒子的邊記作1.

#include #include #include #includeusing namespace std;

class huffman

};huffman::huffman()

huffman::huffman(char a, int weight):elementchar(a),weight(weight)

//遞迴輸出哈夫曼值

void huffmancode(huffman & h)

cout << h.elementchar << "的哈夫曼編碼是:" << s << endl;

return;

} //左孩子

huffmancode(*h.leftchild);

//右孩子

huffmancode(*h.rightchild);

}int main()

//如果j !=i 則略過此次迴圈

else

continue;

for(j = i; j < n; j++)

cout << h << "次" << endl;

m[k] = h;

k++;

} //哈夫曼編碼

huffman huffmantemp;

vector < huffman > huffmanqueue;

//初始化佇列

for(int i = 0; i < k; i++)

//得到哈夫曼樹所有節點

int huffmanqueue_index = 0;

sort(huffmanqueue.begin(), huffmanqueue.end());

while(huffmanqueue.size() < 2 * k - 1)

//把所有節點構造成哈夫曼樹

int step = 0;//步長

while(step + 2 < 2 * k)

}step += 2;

} //cout << huffmanqueue.size() << endl;

//序列最後乙個元素,即哈弗曼樹最頂端的節點

huffmantemp = huffmanqueue.back();

huffmancode(huffmantemp);

return 0;

}

哈弗曼編碼 哈弗曼樹

哈弗曼編碼是依賴於字元使用頻率來建立的一種編碼,通過把使用頻率低的字元分配相對較多的01編碼,而使用頻率高的分配相對較低的01編碼,來建立最小的帶權路徑長度的樹,來最大化的獲得編碼儲存空間的一種編碼規則。這個樹稱為哈弗曼樹,也稱為最優二叉樹。這樣可以確定每乙個字元的編碼不可能成為其他字元編碼的坐子串...

哈弗曼編碼

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 相...