************************************ Greedy Algorithm ************************************ Huffman Coding ==================================== Huffman coding is a lossless data compression algorithm. The idea is to assign variable-length codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The most frequent character gets the smallest code and the least frequent character gets the largest code. The variable-length codes assigned to input characters are Prefix Codes, means the codes (bit sequences) are assigned in such a way that the code assigned to one character is not the prefix of code assigned to any other character. This is how Huffman Coding makes sure that there is no ambiguity when decoding the generated bitstream. Give a character to frequency map, print out the Huffman coding of each character. .. code-block:: none input: {{'a',4}, {'b',5}, {'c':7}, {'d':1}} root+(17) / \ +(10) c(7) / \ +(5) b(5) / \ a(4) d(1) 0 -> left child, 1 -> right child, we can make a rule that left child is greater than right child, or vice versa. map: a: 000 b: 01 c: 1 d: 001 encoding: input: abc , output: 000011 decoding: input: 00011, output: abc ---- There are two key points of huffman-coding: 1. Priority queue. 2. Greedy algorithm to decode. .. literalinclude:: code/huffman_coding_test.cpp :language: c++ :lines: 4-69 :emphasize-lines: 2-12,14-27 :linenos: :name: ood_ticket_price :caption: Huffman coding can be implemented with a minheap .. only:: html - https://www.programiz.com/dsa/huffman-coding - https://www.youtube.com/watch?v=co4_ahEDCho - https://www.youtube.com/watch?v=saofdNsZiYY - https://www.1point3acres.com/bbs/thread-883056-1-1.html Maximum Length of Pair Chain ================================== .. only:: html - https://leetcode.com/problems/maximum-length-of-pair-chain/