【算法基础】AcWing 148. 合并果子 (Huffman树 |优先队列|小根堆)

在这里插入图片描述


题目描述

题目链接

思路

在这里插入图片描述

需要用到优先队列 的小根堆,保证每次合并最小的堆,并且支持删除插入交换操作,使得每次左边的值最小。

C++代码

#include <bits/stdc++.h>
using namespace std;

int main () {
    
    
    int n;
    cin >> n;
    priority_queue<int, vector<int>, greater<int>> heap;
    while (n --) {
    
    
        int x;
        cin >> x;
        heap.push(x);
    }
    int res = 0;
    while (heap.size() > 1) {
    
    
        int x = heap.top();
        heap.pop();
        int y = heap.top();
        heap.pop();
        res += x + y;//合并
        heap.push(x + y);
    }
    cout << res << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_49486457/article/details/124005631