Huffman Tree--greed
Huffman tree: Given n weights as the leaf node of n, constructs a binary tree, if the length of the path with the right to the smallest, called such a two-fork tree is the optimal binary tree, also known as Huffman Tree (Huffman tree). Huffman tree is a tree with the shortest length of the weighted path, and the nodes with larger weights are closer to the root.
Such topics generally calculate Huffman tree path total value, the use of greedy selection of the nature of each time from the team to remove two edge and the smallest tree merged into a new tree into the queue (priority queues, to ensure that the first element of the team the smallest), each time the new tree weights, when there is only one tree in the team end algorithm;
priority_queue<Long Long,vector<Long Long>,greater<Long Long> >Q;//priority queue, which makes the element value small priority, (the default element value large priority);Long LongHuffman ()//Huffman tree, greedy algorithm{ Long Longres=0;//Minimum cost while(Q.size () >=2){//Merge the smallest two elements at a time (at the head of the team); Long LongA=q.top (); Q.pop (); Long Longb=q.top (); Q.pop (); Q.push (A+b); Res+=a+b;//Calculate the cost } returnRes;}intMain () { while(cin>>N) { while(!q.empty ()) Q.pop (); while(n--){ Long Longtmp; CIN>>tmp; Q.push (TMP); //Direct Queue} cout<Endl; } return 0;}
Huffman greedy Algorithm
Huffman Tree--greed