题解 | #搬水果#用小根堆依次弹出两个元素,相加后插入堆。

搬水果

https://www.nowcoder.com/practice/e4c775b0f3ee42a4bb72c26d2e1eef8a

#include<iostream>
#include<queue>
using namespace std;
int main() {
    int n;
    while (cin >> n) {
        if (n == 0) break;
        priority_queue<int, vector<int>, greater<int>> pq;
        while (n--) {
            int num;
            cin >> num;
            pq.push(num);
        }
        int ans = 0;
        while (pq.size() > 1) {
            int a = pq.top();
            pq.pop();
            int b = pq.top();
            pq.pop();
            pq.push(a + b);
            ans += a + b;
        }
        cout << ans << endl;
    }
    return 0;
}

全部评论

相关推荐

07-07 14:30
复旦大学 Java
遇到这种人我也不知道说啥了
无能的丈夫:但我觉得这个hr语气没什么问题啊(没有恶意
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务