题解 | #搬水果#

搬水果

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

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

int main() {
    int n;
    while(cin >> n){
        if(n == 0) continue;
        priority_queue<long,vector<long>, greater<>> q;
        
        while(n--){
            int fruit;
            cin >> fruit;
            q.push(fruit);
        }
        long long answer = 0; //记录带权路径长度和
        while(q.size() > 1){
           long a = q.top();
           q.pop();
           long b = q.top();
           q.pop();
           answer += a + b; //这里要注意 在原有answer基础上加
           q.push(a + b); //新节点权值 加入队列
        }
        cout << answer << endl; //最后的answer即为结果
    }
    
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务