Write this thing, I am also deeply feel the weakness of their data structure, ridiculous is I always thought that learning can also, the result of a heap structure on the dry I half a month, just understand a probably =, I was drunk
Realization of BinaryTree.h two fork tree
/*** Book: Algorithmic Analysis and Design * Features: This header file is designed to implement a two-tree * file: binarytree.h* time: December 15, 2014 18:35:51* Author: cutter_point*/// _ooooo_//o8888888o//88 ". "88//(| -_- |) o\ =/o//____/'---' \____//. ' \\| |// `.// / \\||| : ||| // // / _||||| -:- ||||| - // | | \\\ - /// | |// | \_| ''\---/'' | |// \ .-\__ `-` ___/-. /// ___`. .' /--.--\ `. . __// ."" ' < '. ___\_<|>_/___. ' > ' ".//| | : `- \`.; `\ _ /`;. `/ - ` : | |// \ \ `-. \_ __\ /__ _/ .-` / /// ======`-.____`-.___\_____/___.-`____.-'======// `=---='//// .....//.....//.....//......//Buddha-Town Building Bug----------------- Office Building, writing Room programmer;//program staff write procedures, and take the program for drinks. Sober only on the internet to sit, drunk also to sleep under the net,//Wine drunk Awake day after day, online network next year. I hope the old computer, do not want to bow to the boss before;//Mercedes-Benz BMW is interesting, bus self-programmers. Others laugh at me crazy, I laugh at my life is too cheap,//Don't see the street pretty sister, which is the programmer? #include <iostream>using namespace Std;template<class t>struct btnode{t data;//This is the value of the root node of the two fork tree btnode<t > *lchild, *rchild;//are left and right children Btnode ()//constructor {lchild = Rchild = nullptr;//initialized to null}//constructor number second Btnode (const T &val, Btnode <T> *CHILDL = nullptr, btnode<t> *childr = nullptr) {//This is also initialized for the current binary tree data = Val;lchild = Childl;rchild = Chi LDR;} Copy the corresponding binary tree, this copy is not the kind of tree that only makes children and right children a number, but copies a bunch of them./This is it? This binary tree creates a new memory space, saves the same thing, and returns this new tree, content as btnode<t>* Copytree () {btnode<t> *nl, *nr, *nn;//copy this if (&data = = NULL) return null;//The current corresponding tree is empty NL = Lchild->copytree ( );//Copy the left side of nr = Rchild->copytree ();//Copy the right side to NN = new btnode<t> (data, NL, NR);//create this binary tree return nn;}};/ /Two fork Tree object class Template<claSS T>class binarytree{void Destroy (btnode<t> *&r);//This is to destroy two fork tree void preorder (btnode<t> *r); void Inorder (btnode<t> *r); void Postorder (btnode<t> *r); int Height (const btnode<t> *r) Const;int Nodecount (const btnode<t> *r) const;public:btnode<t> *root; Root node BinaryTree ();//constructor ~binarytree ();//destructor void Pre_order (); void In_order (); void Post_order (); int treeheight () Const;int treenodecount () const;void destroytree (); void Maketree (T pData, binarytree<t> lefttree, BinaryTree< T> righttree); void change (btnode<t> *r);};/ /the implementation of the corresponding class Template<class T>binarytree<t>::binarytree () {root = NULL;} Template<class T>binarytree<t>::~binarytree () {}template<class t>void BinaryTree<T>::P re_ Order () {preorder (root);} Template<class t>void Binarytree<t>::in_order () {inorder (root);} Template<class t>void binarytree<t>::P Ost_order () {postorder (root);} Template<class T>int Binarytree<t>::treeheight () Const{return Height (root);} Template<class t>int binarytree<t>::treenodecount () Const{return nodecount (root);} Template<class t>void binarytree<t>::D estroytree () {Destroy (root);} Template<class t>void binarytree<t>::P reorder (btnode<t> *r)//traverse the output of this tree all data, first root about the order {//root around if (r! = NULL) {cout << r->data << '; Preorder (r->lchild);//Recursive call to Preorder (R->rchild);}} Template<class t>void Binarytree<t>::inorder (btnode<t> *r)//This is the traversal order is first left then Root then right {//Left Right if (r! = NULL) {inorder (r->lchild); cout << r->data << "; inorder (R->rchild);}} Template<class t>void binarytree<t>::P ostorder (btnode<t> *r)//This is the first left then the right end is the root {//around if (r! = NULL) { Postorder (R->lchild); Postorder (r->rchild); cout << r->data << ";} This is the count of how many nodes Template<class t>int binarytree<t>::nodecount (const btnode<t> *r) const{if (r = = NULL) Return 0;//This no node Elsereturn 1 + nodecount (r->lchild) + nodeCount (r->rchild);//current node + left node + right node}//This is to swap all nodes of the two-fork tree, note here is all, not a single few template<class t>//or old routines, Exchange the root first, then into their sub-nodes in the left and right exchange void Binarytree<t>::change (btnode<t> *r) {btnode<t> *p;//This is used to exchange the intermediate variable if (r) {p = R->lchild;r->lchild = r->rchild;//The right side of the node is placed to the left to R->rchild = p;//to the left to the right position change (r->lchild);// Switch all nodes on the left subtree to change (r->rchild);//Swap all nodes on the right subtree}}//this free subtree is released one by one Template<class t>void binarytree<t ::D Estroy (btnode<t> *&r)//Here is a reference pointer, a little confused {if (r! = NULL) {Destroy (r->lchild);// First, the left node to free space Destroy (r->rchild);//Then release all the nodes on the right delete r;//the root node is also released r = nullptr;//set to empty}}//How many node template is on the longest side of the two-fork tree <class t>int binarytree<t>::height (const btnode<t> *r) const{if (r! = nullptr) return 0;//no subtree else{int LH, rh;//length lh = height (r->lchild), RH = height (r->rchild),//left and right side of the long selected return 1 + (LH > RH LH:RH);//The longest node Plus to}}//create a new two-fork tree, this binary tree contains Lefttree and Righttreetemplate<class t>void binarytree<t>::maketree (T PDATA, binarytree<t> lefttree, binarytree<t> righttree)//Here two sub-trees are not pointers {root = new btnode<t> (); root- >data = Pdata;root->lchild = Lefttree.root;root->rchild = righttree.root;//Note that this parameter is not a pointer, Then the new subtree is built and the two parameters are completely irrelevant, the big deal is the same value}
Minimum heap Implementation MinHeap.h
/*** Book: Algorithmic Analysis and Design * Features: This header file is designed to implement a two-tree * file: binarytree.h* time: December 15, 2014 18:35:51* Author: cutter_point*/// _ooooo_//o8888888o//88 ". "88//(| -_- |) o\ =/o//____/'---' \____//. ' \\| |// `.// / \\||| : ||| // // / _||||| -:- ||||| - // | | \\\ - /// | |// | \_| ''\---/'' | |// \ .-\__ `-` ___/-. /// ___`. .' /--.--\ `. . __// ."" ' < '. ___\_<|>_/___. ' > ' ".//| | : `- \`.; `\ _ /`;. `/ - ` : | |// \ \ `-. \_ __\ /__ _/ .-` / /// ======`-.____`-.___\_____/___.-`____.-'======// `=---='//// .....//.....//.....//......//Buddha-Town Building Bug----------------- Office Building, writing Room programmer;//program staff write procedures, and take the program for drinks. Sober only on the internet to sit, drunk also to sleep under the net,//Wine drunk Awake day after day, online network next year. I hope the old computer, do not want to bow to the boss before;//Mercedes-Benz BMW is interesting, bus self-programmers. Others laugh at me crazy, I laugh at my life is too cheap,//Don't see the street pretty sister, which is the programmer? #include <iostream>using namespace std;/* If you are looking for the minimum, at least O (n), because at least one of the elements must be traversed, and the advantage of the smallest heap is its dynamic maintainability. If an array, when an element of an array changes (add, delete, or modify), you do not know how the minimum value will change (otherwise, if the minimum value is deleted, if you want to find the minimum value, you also need to re-scan the array. Of course you would think of an array if it's orderly? But you have to maintain arrays at any time to ensure that arrays are ordered, which also requires O (N) complexity when inserting data. In contrast, the minimum heap requires only O (Logn) complexity, is not very good (the first person to design this data structure, really very good AH). In addition, the smallest heap (as if the largest heap, forget, anyway two is a matter) also can be as a priority queue (that is, in order to rank the importance of the team, each time the team first element, people cut the queue is OK, O (LOGN) on the line), this should be its most common application */// This is the heap used to store all the data template<class t>class minheap//The smallest heap is a node smaller than the sub-node two fork tree, the largest heap is the node is larger than the sub-node of the two-fork tree {T *heap;//element array, position No. 0 also stores elements int currentsize; The current number of elements int MaxSize; The maximum number of elements that can be accommodated void Filterdown (const int start, const int end); Adjust from top to bottom so that the keyword small node is on the upper void Filterup (int start); Adjust public:minheap from bottom to top (int n = 1000);//constructor ~minheap (); bool Insert (consT T &x);//Insert Data T removemin ();//delete smallest element T getmin ();//get minimum element bool IsEmpty () const;//determine if NULL bool Isfull () const;// is full void clear ();//clear void look ();//View all elements};template<class t>void Minheap<t>::look () {for (int i = 0; i < Ma Xsize; ++i) cout << heap[i] << Endl;} void Filterdown (const int start, const int end); Adjust from top to bottom to make the keyword small node on template<class t>void minheap<t>::filterdown (const int start, const int end) {int i = Star T, j = 2 * i + 1;//i represents the beginning of the data t temp = heap[i];//temp means I currently point while (J <= end)//As long as J does not reach the trailing {if ((J < End) && (heap[ J] > Heap[j + 1]))//As long as J is in front of the last one, and the number of J is greater than the number in the back {++j;//then go directly to the next}//ifif (temp <= heap[j]) break;// If the value of this I point is smaller than the value J points to, then regardless of else{//if temp is larger than J, that is, the front is larger, and this j is smaller than the back, that is, the middle J is the smallest, in this three number heap[i] = Heap[j];i = J;j = 2 * j + 1;} Esle}//whileheap[i] = temp;//Refreshes the value of I, this is the root element}//void minheap<t>::filterdown (const int start, const int end)//void Filterup (int start); Adjust Template<class t>void minheap<t>::filt from bottom to topErup (int start) {int J = start, I = (j-1)/2;//i points to J parent Node T temp = heap[j];while (J > 0) {if (Heap[i] <= temp) Break;el SE{HEAP[J] = Heap[i];j = I;i = (i-1)/2;} ELSE}//WHILEHEAP[J] = temp;} void Minheap<t>::filterup (int start)//constructor implementation Template<class t>minheap<t>::minheap (int n) { MaxSize = n;//The maximum number of elements that can be accommodated heap = new t[maxsize];//creates a node of type T with MaxSize currentsize = 0;//not yet an element}//destructor Template<class T>minheap<t>::~minheap () {//Recycle all controls delete []heap;} Insert Data Template<class t>bool minheap<t>::insert (const T &x) {if (currentsize = = MaxSize)// If the element has been fully filled with return false;//return cannot be inserted heap[currentsize] = x;//assigns x to the current position, then there are 0 to currentsize elements that are currentsize+1 elements Filterup ( CurrentSize);//Insert the element into the sort Currentsize++;return true;//Insert success}//t removemin (); Remove the smallest element template<class t>t minheap <t>::removemin () {T x = heap[0];heap[0] = heap[currentsize-1];//assigns the last element to the first element currentsize--;//deletes an element, Number minus one filterdown (0, CurrentSize-1);//Adjust the new root node return x; Return the removed element to}//t getmin ();//Get the smallest element template<class t>t minheap<t>::getmin () {return heap[0];} BOOL IsEmpty () const;//determine if the empty Template<class t>bool minheap<t>::isempty () const{return currentsize = = 0;/ /Return to True Then there is no element is empty}//bool isfull () const;//is full template<class t>bool minheap<t>::isfull () Const{return CurrentSize = = MaxSize;} void clear ();//Empty Template<class t>void minheap<t>::clear () {currentsize = 0;//directly start overwriting data}/*** <p> My TM is finally practicing! Hello World has finally printed out! %>_<% I Cry first (excited) will ~~~<p>* @version 1.0.1* @since JDK 1.6* @author jacksen**///to the brave man who finally came here://You are chosen by God, heroic, no Laborious, sleepless to modify//Our programming Knight of this most tricky code. You, our Savior, the Dragon and the Phoenix,//I want to say to you: Never give up, never be disappointed in yourself, never run away, fail yourself. Never cry, never Say goodbye. Never lie to hurt yourself. To the brave man who finally came here://You are chosen by God, heroic, painstaking, sleepless to modify//Our most tricky code of the programming knight. You, our Savior, the Dragon and the Phoenix,//I want to say to you: Never give up, never be disappointed in yourself, never run away, fail yourself. Never cry, never Say goodbye. Never lie to hurt yourself. To the brave man who finally came here://You are chosen by God, heroic, painstaking, sleepless to modify//Our most tricky code of the programming knight. You, our Savior, the Dragon and the Phoenix,//I want to say to you: Never give up, never be disappointed in yourself, never run away, fail yourself. Never cry, never Say goodbye. Don't everLie to hurt yourself. Top Top/Top Top/Top Top//top Top/Top Top/Top Top/Top Top/Top Top/Top top Top Top//top top//top top//top Top/Top Top/Top Top/Top Top/Top Top/ /top Top/Top Top/Top Top/Top Top/Top Top//top top Top//top top Top Top/top Top/Top Top/Top Top/Top Top/Top Top/Top top Top/top Top Top/ /top Top top/*code are far away from bugs with the animal Protecting*┏┓┏┓*┏┛┻━━━┛┻┓*┃┃*┃━┃*┃┳┛┗┳ ┃*┃┃*┃┻┃*┃┃*┗━┓┏━┛*┃┃ God beast bless *┃┃ code no bug! *┃┗━━━┓*┃┣┓*┃┏┛*┗┓┓┏━┳┓┏┛*┃┫┫┃┫┫*┗┻┛┗┻┛**//****----------Dragon is here!----------/ ┏┓┏┓┏┛┻━━━┛┻┓┃┃┃━┃┃┳┛┗┳┃┃┃┃┻┃┃┃┗━┓┏━┛ ┃┃   ;┃┃ ┃┗━━━┓ ┃┣┓ ┃┏┛ ┗┓┓┏━┳┓┏┛&n bsp; ┃┫┫┃┫┫ ┗┻┛┗┻┛ ━━━━━━ ━━━━━━*//** ┏┓┏┓┏┛┻━━━┛┻┓┃┃┃━┃┃> <┃┃┃┃ ... ⌒ ... ┃┃┃┗━┓┏━┛ ┃┃code is far away from bugs with the animal protecting ┃┃ god beast Bless, code without bug& nbsp; ┃┃ ┃┃ ┃┃ ┃┃ ┃┗━━━ ┓ ┃┣┓ ┃┏┛ ┗┓┓┏━┳┓┏┛ ┃┫┫┃┫┫&n bsp; ┗┻┛┗┻┛*//***┏┓┏┓+ +*┏┛┻━━━┛┻┓+ +*┃┃*┃━┃++ + + +* ████━████┃+*┃┃+*┃┻┃*┃┃+ +*┗━┓┏━┛*┃┃*┃┃ + + + +*┃┃code are far away from bugs with the animal protecting*┃┃+ god beast Bless, code without Bug*┃ ┃*┃┃+*┃┗━━━┓+ +*┃┣┓*┃┏┛*┗┓┓┏━┳┓┏┛+ + + +* ┃┫┫┃┫┫*┗┻┛┗┻┛+ + + +*///1 sheep = = one SHEEP//2 sheep = = Two Sheeps//3 sheep = = Three Sheeps//4 sheep = = Four Sheeps//5 sheep = = Five Sheeps//6 sheep = = SIX Sheeps//7 Sheep = = Seven Sheeps//8 sheep = = Eight Sheeps//9 sheep = = Nine Sheeps//10 sheep = = Ten Sheeps//11 sheep = = Eleven Sheeps//12 only sheep = = Twelve SHEEPS//13 sheep = = Thirteen Sheeps//14 sheep = = Fourteen Sheeps//15 only sheep = = Fifteen sheeps//16 sheep = = Sixteen Sheeps//17 sheep = = Seventeen Sheeps//18 sheep = = Eighteen Sheeps//19 sheep = = Nineteen sheeps//20 only sheep = = Twenty Sheeps//21 sheep = = Twenty One SHEEPS//22 only Sheep = = Twenty two sheeps//23 sheep = = Twenty three sheeps//24 sheep = = Twenty four sheeps//25 sheep = = Twenty five sheeps//26 sheep = = Twent Y six Sheeps//27 sheep = = Twenty seven sheeps//28 sheep = = Twenty eight sheeps//29 sheep = = Twenty nine sheeps//30 sheep = = Thirty sheeps/ /Now sleepy, OK, don't change the following code, Sleep ~~/*** born * | | * || * \/* \/* youth * (age = rand (20,25))) "==============* | | || * || || * || Bless All Developers | | * || Always Young || * || || * \ / || * \/ || * (<= Age <= 25) ===============* | | * || * \/* \/* and other dead states */
Huffman.cpp
The main function, here is a bit of a friend problem, temporarily did not think of a good way
/*** Book: Algorithmic Analysis and Design * Features: Implementing Havermann Encoding * File: huffman.cpp* time: January 3, 2015 17:52:30* Author: cutter_point*/#include "BinaryTree.h" # Include "MinHeap.h" #include <iostream>using namespace Std;template<class t>class huffman;// First declare the Huffman class Template<class t>binarytree<int> Huffmantree (T f[], int n);//This is the declaration of a global Havermann tree function template< Class T>class Huffman{friend binarytree<int> Huffmantree (T [], int);//friend function public://operator overload operator T () const { return weight; }/*private:*///here to make a private problem, do not know whether it is a compiler issue, or My code is wrong, I am testing for half a day, think the compiler is jerking off = =binarytree<int> tree;//Havermann structure is composed of a binary tree and weights of t weight;};/ /algorithm Huffmantreetemplate<class t>//establish a two-fork tree binarytree<int> huffmantree (T f[], int n) to encode//This is all the numbers, and the number of { First generate a single node tree huffman<t> *w = new Huffman<t>[n + 1];//generate 2 empty two fork tree binarytree<int> z, zero;for (int i = 1; I & lt;= N; ++i) {Z.maketree (I, Zero, zero);//Make a vacancies two fork tree, the first sequence number is Iw[i].weight = f[i];//Assign the weight value to the corresponding node W[i].tree = z;//The empty tree as the initial assignment to him}// The minimum heap is the first to merge the smallest minheap
Summarize
Haha, this program time span of up to one year oh, oh above that traverse result a little flaw, is output not result but node number, 0 represents later merge node, in fact I think the output weight value will be better, that is, in this below again output weights, but the code is not thinking so much when writing, Add this and trouble = =, say the idea, is to return the value is not to return to the tree, but instead of returning a Huffman structure of the whole binary tree, so that the traversal can be accompanied by output weight, and to do so, Then in the BinaryTree.h header file can not use that function to traverse, you have to re-write a function to Huffman to traverse, so I don't do that.
"Algorithm Design and Analysis" 8, Havermann coding, greedy algorithm implementation