Preparing for a quick refresher --day9

Huffman trees and Huffman coding related.

Huffman main problem to solve: there are n heap, how they will be synthesized into a heap in the process can consume the least. (Each selected two merge, when the consumption of two times the sum of physical strength)

Each stack two minimal selected line, and with a new node is added after the completion of the merger.

You can use the priority queue implementation. (Default priority queue is descending, ascending with greater change)

#include<queue>
#include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;
int main()
{
    priority_queue<int,vector<int>,greater<int> >q;
    int n;
    scanf("%d",&n);
    int temp,ans=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&temp);
        q.push(temp);
    }
    int temp1,temp2;
    while(q.size()>1)
    {
        temp1=q.top();
        q.pop();
        temp2=q.top();
        q.pop();
        years + = + temp1 time2;
        q.push(temp1+temp2);
    }
    printf("%d ",q.top());
    printf("%d",ans);
    return 0;
}
View Code

Huffman coding, coding to ensure that at various points in the process can not be a prefix other nodes lead to erroneous interpretation.

All points are among the leaf nodes. This ensures that they are not the same prefix. Left Right 0 1.

With regard to the right to interpretation: the right point and into the right side. Huffman tree in the above application scenarios. * Own right point right side (default 1, n Article 1 n) is the heap consumption

In the encoding process, the number of points in the point that the right appears inside, each edge is 1, so that the calculated total string length.

To reduce the overall length, also in accordance with an occurrence frequency of consumption of the Huffman tree is complete, all points on the leaves.

The actual process used to replace the priority queue can easily calculate the consumption. Seeking specific encoding requires the implementation tree. (Temporarily Chaogang)

Guess you like

Origin www.cnblogs.com/tingxilin/p/12361050.html