Analysis of C + + Huffman coding and decoding implementation _c language

Source: Internet
Author: User
Tags array length

A Background information:

Given n weights as n leaf nodes, a binary tree is constructed, and if the length of the weighted path is minimized, the two-fork tree is called the optimal binary tree, also known as Huffman Tree (Huffman). Huffman tree is a tree with the shortest length of weighted path, and the node with larger weights is nearer to the root.

Two Implementation steps:

1. Construction of a tree Huffman tree

2. Create a Huffman code table according to the created Huffman tree

3. Input a series of Huffman sequence, output original characters

Three Design idea:

1. First of all to construct a Huffman tree, Huffman tree node structure including weight value, parents, children, if the N characters to construct a Huffman tree, then a total of nodes 2n-1; Before construction, initialization, initialization is to the parents, the child's subscript values are assigned to 0; then enter the weights of each node in turn

2. The second step is through the n-1 cycle, each time first find the input weight of the smallest two nodes, the weights of the two nodes are added to a new node, and the left child of the new node is the node with the smallest weight, and the right child is the second small node of the weighted value; Given that the nodes found above are all nodes with a parent of 0, In order to correctly find the two nodes with the lowest weights in the remaining nodes. The parents of the two nodes whose weights are the smallest in each loop are assigned 0 (i). In this way through the n-1 cycle, operation, created a Huffman tree, which, The first n nodes are the leaves (the input of the character node) after the n-1 is a node of 2 degrees.

3. The idea of coding is to reverse code, starting from the leaf node, backtracking up, if the node is traced back to the last node of the left child, save "0" in the record-encoded array, or "1", and note that it is stored backwards until the root node is encountered (the node parent is 0) and each loop is encoded into the root node. Put the code in the coded table and start coding the next character (leaf)

4. Decoding the idea is to read a string of Huffman sequence, read "0" from the root node of the left child continue to read, read "1" from the right child to continue, if read to a node of the left child and right child are all 0, if is the description has read a leaf (character), translated a character success, The characters represented by the leaf node exist in an array that stores the translated characters, and then continue to read from the root node until you finish reading the Huffman sequence and exit the translation loop when you encounter the Terminator.

Four Source:

/*************************************** Purpose: 1. According to the input character code set and its weight set, the Huffman tree is constructed and the Huffman encoding of each character is printed 2. Input Huffman code sequence, output original character code author: Dmego Time: 2016-11-11 ****************************************/#include <iostream> #define MAX_MA 1000 #define MAX_ZF

using namespace Std; Huffman Tree Storage represents the typedef struct {int weight;//node weights int parent, lchild, rchild;//parent, left child, right child's subscript}htnode,*huffmantree; Dynamically allocating arrays to store Huffman tree nodes//Huffman encoded table storage representation typedef char **HUFFMANCODE;//dynamic allocation array Storage Huffman encoding//returns two parent domain 0 with the lowest weight value of the subscript void Select (  Huffmantree ht, int n, int &s1, int &s2) {/*n represents the length of the HT array///The first two for loops find the point (character) for the smallest weights in all nodes (int i = 1; I <= N i++) {////using the For loop to find a node with a parent of 0 if (ht[i].parent = = 0) {S1 = i;//s1 initialized to I break;//to exit the loop immediately after finding one) for (int i = 1 ; I <= N;
   i++) {/* Use the For loop to find the smallest of all node (character) weights and ensure that the parent of the node is 0*/if (Ht[i].weight < ht[s1].weight && ht[i].parent = 0)
 S1 = i; (int i = 1; I <= n; i++) {//Use the For loop to find a node with a parent of 0 and cannot be s1 if (ht[i].parent = = 0 = +) for the second small point (character) in all nodes of the last two for loops. ;&Amp I!= s1) {s2 = i;//s2 initialized to I break;//to exit the loop immediately after (int i = 1; I <= n; i++) {*/* Use the For loop to find all node (character) weights Two small one, the node satisfies cannot be S1 and the parents are 0*/if (Ht[i].weight < ht[s2].weight && ht[i].parent = 0 && i!= s1) s2 = i
 ; }//Constructs Huffman tree void Createhuffmantree (huffmantree &ht, int n) {/*-----------initialization work-------------------------*/if (N &
 lt;= 1) return;
 int m = 2 * n-1;
 HT = new Htnode[m + 1]; for (int i = 1; I <= m ++i) {//the subscript of the parent, left child, and right child in the 1~m unit is initialized to 0 ht[i].parent = 0; Ht[i].lchild = 0;
 Ht[i].rchild = 0; for (int i = 1; I <= n; ++i) {cin >> ht[i].weight;//the weight of the leaf node in the first n cells of the input}/*-----------create a job------------------
 ---------*/int s1,s2;
  for (int i = n + 1; I <= m ++i) {//through n-1 selection, delete, merge to construct Huffman tree Select (HT, i-1, S1, S2); /*cout << ht[s1].weight << "," << ht[s2].weight << endl;*//* Change the parental domain of s1,s2 from 0 to I (equivalent to removing the two nodes, which
  Two nodes no longer participate in the Select () function) */ht[s1].parent = i;
  Ht[s2].parent = i; S1, and S2 respectivelyFor I the left and right child ht[i].lchild = S1;
  Ht[i].rchild = s2;
 The weights of node I are the sum of s1,s2 weights and ht[i].weight = Ht[s1].weight + ht[s2].weight; }//From leaves to root reverse the Huffman code for each character, stored in the Code table HC void Creathuffmancode (Huffmantree HT, huffmancode &hc, int n) {HC = new char*[n + 1];//allocating n-character encoded table space char *CD = new char[n];//allocating temporary storage character encoding dynamic space cd[n-1] = ' = '//encoding terminator for (int i = 1; I <= N; i+
  +)/character encoding one by one {int start = N-1;//start start pointing to the last, that is, the encoder terminator position int c = i;  int F = ht[c].parent;//f the parent while (F!= 0) of node C//starts backtracking from the leaf node until the root node {--start;//goes back once, and the start points forward to a position if (ht[f].lchild
   = = c) Cd[start] = ' 0 '///node C is the left child of F, then cd[start] = 0;
   else Cd[start] = ' 1 '//otherwise C is the right child of f, cd[start] = 1 c = f; F = ht[f].parent;//continue up backtracking} hc[i] = new char[n-start];//allocate space for the first character encoding strcpy (Hc[i], &cd[start]); The first address of the code to be obtained from cd[
Start] is copied to the current line of HC} Delete cd; }//Huffman decoding void Trancode (Huffmantree ht,char a[],char zf[],char b[],int N) {/* HT is already a created Huffman tree a[] used to pass in binary encoding b[] used to record translated words Character Zf[] is a huffman tree with the leaves corresponding to the characters (leaf subscript and character subscript corresponding) n is the number of characters, equivalent to zf[]Array length/int q = 2*n-1;//q subscript int k = 0;//record stores the subscript int i = 0 for a character array to be initialized to a root node for (i = 0; a[i]!= '; i++) {//for loop end condition is that the read character is Terminator (binary encoded)//This code block is used to determine whether the read binary character is 0 or 1 if (a[i] = = ' 0 ') {/* Read 0, the root node (HT [Q])
  The left child's subscript value is assigned to q the next cycle of the ht[q] as a new root node * q = ht[q].lchild;
  else if (a[i] = = ' 1 ') {q = ht[q].rchild; }//This code block is used to determine if HT[Q] is a leaf node if (Ht[q].lchild = = 0 && ht[q].rchild = 0) {/* is a leaf node, indicating that a character has been translated the subscript of the character is found under the leaf node Superscript/b[k++] = zf[q];//The word labeled Q assignments to the character array b[] Q = 2 * n-1;//Initialization q is the root node of the subscript//continue to translate the next character from the Huffman tree at the beginning of the root node}///decoding completed, used to record
The array of characters is returned incorrectly because there is no terminator output, so it is followed by adding a terminator to the array last */b[k] = ';
 }//Menu function void menu () {cout << Endl;
 cout << "┏〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓┓" << Endl;
 cout << "┃★★★★★★★ Huffman coding and decoding ★★★★★★★┃" << Endl; cout << "┃1.
 Create Huffman Tree ┃ "<< Endl; cout << "┃2.
 Carry on Huffman code ┃ "<< Endl; cout << "┃3.
 Carry on Huffman decoding ┃ "<< Endl; cout << "┃4. BackOut of the program ┃ "<< Endl;
 cout << "┗〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓┛" << Endl;
 cout << "<>< Note: space characters with '-' instead ><> ' << Endl;
cout << Endl;
 } void Main () {int falg;//records the number of characters to encode Char a[max_ma];//store input binary character Char b[max_zf];//store the translated character Char zf[max_zf];//store characters to encode
 Huffmantree HT = null;//initialization tree is an empty number huffmancode HC = null;//Initialization encoded table is an empty Table menu ();
  while (true) {int num;
   cout << "<>< Please select function (1-Create 2-code 3-Decode 4-exit) ><>:";
   CIN >> Num;
    Switch (num) {case 1:cout << "<>< Please enter the number of characters ><>:";
    Cin >> Falg; Dynamic request Falg A length character array to store the characters to encode/*char *zf = new char[falg];*/cout << "<>< Please enter" << falg <& Lt
    "Character: ><>:";
    for (int i = 1; I <= falg i++) cin >> Zf[i];
    cout << "<>< Please enter the" << falg << "character of the weight ><>:";
    Createhuffmantree (HT, FALG);//Invoke function to create Huffman tree cout << Endl; CouT << "<>< Create Huffman success!"
    , the following is the Huffman tree parameter output ><>: "<< Endl;
    cout << Endl;  cout << "Node i" << "T" << "character" << "\ T" << "Power value" << "\" << "" parents "<<" T "<<
    "Left child" << "T" << "right child" << Endl; for (int i = 1; I <= falg * 2-1; i++) {cout << i << "\ t" <<zf[i]<< "T" << ht[ I].weight << "T" << ht[i].parent << "T" << ht[i].lchild << "T" << Ht[i].rchild <
    < Endl;
    } cout << Endl;
   Break
    Case 2:creathuffmancode (HT, HC, falg);//Invoke function to create Huffman coding table cout << Endl; cout << "<>< Generate Huffman Coding table success!"
    , the following is the output ><&gt of the coding table;: "<< Endl;
    cout << Endl;
    cout << "Node i" << "T" << "character" << "\ T" << "right value" << "\ T" << "code" << Endl; for (int i = 1; I <= falg i++) {cout << i << "\ t" <<zf[i]<< "T" <&Lt
    Ht[i].weight << "T" << Hc[i] << Endl;
    } cout << Endl;
   Break
    Case 3:cout << "<>< Please enter a string of binary encodings you want to translate ><>:";
    /* This enables you to enter a string of binary encodings dynamically, as the final system will automatically add a terminator/CIN >> A;
    Trancode (HT, A, ZF, B, falg);//Call decoding function,/* This can be directly to the array B output, because the end of the array B to add output when the end of the end of the output * * * cout << Endl; cout << "<>< decoding success!"
    The result of translation is ><>: "<< b << Endl;
    cout << Endl;
   Break
    Case 4:cout << Endl; cout << "<>< exit Success!"
    ><> "<< Endl;
   Exit (0);
   Default:break; }//-abcdefghijklmnopqrstuvwxyz//186 64 13 22 32 103 21 15 47 57 1 5 32 20 57 63 15 1 48 51 80 23 8 18 1//0

 00101010111101111001111110001100100101011110110}

Five Run Screenshots:

Original link: http://www.cnblogs.com/dmego/p/6064069.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.