Overview
To discuss the problem of Huffman coding, the idea of coding is variable-length coding. Variable length coding is to make the characters in the character table with high probability of the encoding length of the characters as small as possible, and the high probability of the character encoding length is relatively long. Then also follow the requirements of the prefix code, that is, any one encoding is not the prefix code of other encodings, so as to facilitate decoding.
thinking and realization
For the characters in the following table and the corresponding occurrence probability, there is an encoding tree in the corresponding graph:
It can be easier to see, each leaf node represents a character, from the root node to the leaf node through the path of stitching up, representing the encoding of this character, such as F is 1100,e is 1101, and F and E is the deepest node is the lowest probability of two nodes. This is the Huffman encoded form we require. This optimal form of coding is always a full two-fork tree.
There is a great deal of space in the calculation to demonstrate that the Huffman encoding can be accomplished by using the greedy algorithm, which chooses two nodes with the least probability at a time. This is only the implementation method.
Because every time we need to find the node with the least probability, we can use the minimum priority queue to do it, pop it out and erase it. Note that the number of leaf nodes in the tree is equal to the number of characters, and the number of internal nodes is equal to the number of characters minus one, so the inner node loop needs only n-1 times, N is the number of characters.
Small Gan operation:
#include <iostream> #include <stack>using namespace std; #define MAX_INDEX 11struct Node {int freq;node* left; node* Right;node (): Freq (), Left (null), right (null) {}};//array starts with the number 1th element int left_child (int i) {return i * 2;} int right_child (int i) {return I * 2 + 1;} int parent (int child) {return CHILD/2;} void Swap (node* A, node* b) {node TMP = *A;*A = *B;*B = tmp;} void Print_heap (node* a, int len) {for (int i = 1; i < Len; i++) {cout << a[i].freq << ';} cout << Endl;} /* * Convert a heap of small Gan into small Gan */void min_heapify (node heap[], int root, int n) {int L = left_child (root); int r = Right_child (r oot); int min = root;if (l <= n && heap[min].freq > Heap[l].freq) {min = l;} if (r <= n && heap[min].freq > Heap[r].freq) {min = R;} if (min! = root) {Swap (heap + root, heap + min); Min_heapify (Heap, Min, n);}} /* * Build a small Gan */void build_min_heap (node heap[], int n) {int idx = N/2 + 1;for (int i = idx; I >= 1; i--) {min_heapify (Heap, I, n);}}
Minimum priority queue operation:
/* * Minimum priority queue action to be implemented: * *①insert (s,x) * *②minimum (s) * *③extract_min (s) * *④decrease_key (S,X,K) * *//* * Minimum priority queue */struct Min_priority_queue {node* min_heap;int len;min_priority_queue (node* mh, int L): Min_heap (MH), Len (l) {}};/* * Returns the smallest element */nod e* heap_minimum (min_priority_queue* mpq) {if (Mpq->len < 1) {cout << "min_priority_queue underflow" << E NDL;} return mpq->min_heap + 1;} /* Eject and remove the smallest element */node* heap_extract_min (min_priority_queue* mpq) {if (Mpq->len < 1) {cout << "Min_priority_qu Eue underflow "<< Endl;} This must be a new node to return to, if directly return to the original node, it will result in the next insert, the left and right of the child's pointer to the content changes//new node node* min = new nodes ();//Copy the contents of the smallest node to the new node, Finally, the pointer to the newly created node returns *min = * (Mpq->min_heap + 1), swap (mpq->min_heap + 1, mpq->min_heap + Mpq->len),//delete the popup node, Prevent memory leaks Delete (mpq->min_heap + Mpq->len);//Remove the last node from the heap (Mpq->len)--;//re-maintain the nature of the small Gan min_heapify (mpq->min_ Heap, 1, mpq->len);//Return Minreturn min;} /* * The value of the element that originally was x in the priority queue, changed to K, and maintains the property of the minimum heap */void heap_decrease_key (min_priority_queue* MPQ, int i, node* n) {if (Mpq->min_heap[i].freq < n->freq) {cout << "error: The value to replace is larger than the original value" << Endl;r Eturn;} Mpq->min_heap[i].freq = N->freq;while (i >= 1 && mpq->min_heap[i].freq < mpq->min_heap[parent (i)]. Freq) {Swap (mpq->min_heap + I, Mpq->min_heap + parent (i)), I = parent (i);}} /* * Insert Element */void Heap_insert (min_priority_queue* mpq, node* N) {(Mpq->len) ++;* (mpq->min_heap + mpq->len) = *n;HEA P_decrease_key (MPQ, Mpq->len, n);} /* * Print node array */void print_node_array (node* n_arr, int max_index) {for (int i = 1; I <= max_index; i++) {cout << n_ Arr[i].freq << ';} cout << Endl;}
Huffman encoding to form the encoding tree:
Huffman Coding Tree struct huffman_tree{node *root; Huffman_tree (): root (NULL) {}};/* * Huffman encoded, returns the head node of the encoding tree */void Huffman (min_priority_queue* mpq,huffman_tree* T) {int n = mpq-& Gt;len; Build_min_heap (Mpq->min_heap, N), node* tmp = null;//internal nodes have n-1, so n-1 cycles, each TMP is an internal node, after the formation, and then the TMP into the heap, continue to loop for ( int i = 1; I <= n-1; i++) {tmp = new node (); tmp->left = Heap_extract_min (MPQ); tmp->right = Heap_extract_min (MPQ); tmp->freq = tmp- >left->freq + tmp->right->freq; Heap_insert (MPQ, TMP);} Return Heap_extract_min (MPQ); T->root=heap_extract_min (MPQ);} /* * Middle sequence traversal encoding tree */void print_coded_tree (node* root) {if (root = NULL) {print_coded_tree (root->left); cout << ROOT-&G T;freq << "; Print_coded_tree (Root->right);}} /* * Delete the node of the encoding tree */void delete_coded_tree (node* root) {if (root = NULL) {delete_coded_tree (root->left); node* tmp = root-& Gt;right;delete root;root = Null;delete_coded_tree (TMP);}} int main () {int Freq_arr[max_index + 1] = {0, 10, 4, 8, 20, 7, 6, 3, 11, 1, 5, 25 };node Node_arr[max_index + 1];for (int i = 0; i <; i++) {node_arr[i].freq = Freq_arr[i];} Create a new minimum Priority queue object, apply the above array min_priority_queue* MPQ = new Min_priority_queue (Node_arr, Max_index); huffman_tree* T = new Huffman_tree (); HUFFMAN (mpq,t); Print_coded_tree (T->root); 10 internal nodes and the original 11 leaf nodes, total 21 nodes Delete_coded_tree (t->root); return 0;}
Analysis of Complexity
The formation of small Gan time-consuming O (n), while in Huffman (min_priority_queue* mpq,huffman_tree* T) in the n-1 times for loop, each for is to do a number of times to maintain a small Gan nature of operation, each time the complexity of O (LGN ), so the total is: O (N+N*LGN) =o (NLGN).
The "Introduction to Algorithms" greedy algorithm of the Huffman code