top1编程
← 返回题目
题解

【基础】合并果子

1 条题解

  • 0
    @ 2026-7-28 22:44:48
    #include <bits/stdc++.h>
    using namespace std;
    int main() {
        int n;// n:果子堆的数量
        cin >> n;
        // 定义小根优先队列,堆顶永远是当前数值最小的一堆果子
        priority_queue<int, vector<int>, greater<int>> h;
        for (int i = 0; i < n; i++) {// 读取每一堆果子数量,存入小根堆
            int x;
            cin >> x;
            h.push(x);
        }
        long long s = 0;// s 保存总共消耗的体力
        while (h.size() > 1) { // 堆里超过1堆就持续合并
            int a = h.top();// 取出最小的第一堆
            h.pop();
            int b = h.top();// 取出最小的第二堆
            h.pop();
            s += a + b;// 合并两堆,消耗体力等于两堆之和,累加总体力
            h.push(a + b);// 把合并后的新堆放回堆中
        }
        cout << s << endl;// 输出最小总体力消耗
        return 0;
    }
    
    • 1