Huffman编码

Huffman编码用来解决最小二叉树问题...

用堆来维护,所用用优先队列(稍微修改一下放入方式)每次将两个权值最小的取出来,然后把他们的和再放进去,重复这个操作就可以解决了

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 typedef long long ll;
 5 
 6 int main(){
 7     priority_queue<int>que;
 8     int n, x;
 9     cin>>n;
10     for(int i=0; i<n; i++){
11         cin>>x;
12         que.push(-x);
13     }
14     ll ans=0;
15     while(que.size()>1){
16         int l1=-que.top();que.pop();
17         int l2=-que.top();que.pop();
18         ans+=(l1+l2);
19         que.push(-(l1+l2));
20     }
21     cout<<ans<<endl;
22 
23     return 0;
24 }
原文地址:https://www.cnblogs.com/ledoc/p/6561370.html