AcWing 148. 合并果子

Acwing

哈夫曼树

哈夫曼树的编码,可以通过优先级队列来实现。

#include<iostream>
#include<algorithm>
#include<queue>

using namespace std;
const int N = 1e5 + 10;

// 通过优先级队列来实现自动排序
priority_queue<int, vector<int>, greater<int> > q;

int main()
{
    int n;
    cin >> n;
    
    for (int i = 0; i < n; i ++)
    {
        int a;
        cin >> a;
        q.push(a);
    }
    
    int res = 0;
    
    // 由于每次都会添加进去一个元素,所以看上去是每次取出两个元素,实际上是每次取出一个元素。所以接下来不再额外再加优先级队列中的最后一个元素
    while(q.size() > 1)
    {
        int a = q.top();
        q.pop();
        
        a += q.top();
        q.pop();
        
        res += a;
        
        q.push(a);
    }
    
    cout << res <<endl;
}
posted @ 2021-01-04 23:36  alexemey  阅读(47)  评论(0)    收藏  举报