题干

C++实现
- 从小根堆的选择最小的两个
- 合并加和,然后插入回小根堆
- 然后重复上述两个步骤,直到只剩一个元素
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <queue>
#include <string>
using namespace std;
int main() {
int n;
scanf("%d", &n);
priority_queue<int> pqueue;
for (int i = 0; i < n; i++)
{
int leaf;
scanf("%d", &leaf);
pqueue.push(-1*leaf);
}
int wpl = 0;
while (pqueue.size() >= 2) {
int leaf1 = pqueue.top();
pqueue.pop();
int leaf2 = pqueue.top();
pqueue.pop();
wpl += leaf1 + leaf2;
pqueue.push(leaf1 + leaf2);
}
printf("%d\n", -1 * wpl);
}