洛谷P1090 合并果子 题解 小根堆/优先队列

题目链接:https://www.luogu.com.cn/problem/P1090

解题思路:使用优先队列来维护一个小根堆,每次取出2个堆顶元素,将它们的和加入答案中并且它们的和在此放入堆中。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
int n, a, b, ans;
priority_queue<int, vector<int>, greater<int> > pq;
int main() {
    cin >> n;
    for (int i = 0; i < n; i ++) {
        cin >> a;
        pq.push(a);
    }
    for (int i = 1; i < n; i ++) {
        a = pq.top(); pq.pop();
        b = pq.top(); pq.pop();
        ans += a+b;
        pq.push(a+b);
    }
    cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/quanjun/p/12272543.html