题解
合并果子
1 条题解
-
0
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; // 小根优先队列,每次能快速取出数值最小的堆 priority_queue<int, vector<int>, greater<int>> pq; // 读取每堆果子数量,存入优先队列 for (int i = 0; i < n; i++) { int num; cin >> num; pq.push(num); } // 记录总共消耗的体力 int total_cost = 0; // 剩余堆数大于1时,持续合并 while (pq.size() > 1) { // 取出当前最小的两堆 int a = pq.top(); pq.pop(); int b = pq.top(); pq.pop(); // 计算本次合并消耗的体力,并累加到总和 int cost = a + b; total_cost += cost; // 将合并后的新堆重新加入队列 pq.push(cost); } // 输出最小总体力消耗 cout << total_cost << endl; return 0; }
- 1