Huffman Tree--greed

Source: Internet
Author: User

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

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.