题目大意
输入一串数字。然后每次从中取出两个,相加后把和放回去。这一过程有消耗,大小为这个和的值,问只剩下一个数时产生的最小消耗的总和。
思路
用贪心策略,每次取出的两个数都是最小的。直接上优先队列STL吧!
代码
#include <queue>
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
//freopen("input.txt", "r", stdin);
int n;
while(cin >> n && n) {
priority_queue<int , vector<int>, greater<int> > pq;
for(int i = 0; i < n; i++) {
int t;
cin >> t;
pq.push(t);
}
int cnt = 0;
for(int i = 0; i < n - 1; i++) {
int a = pq.top(); pq.pop();
int b = pq.top(); pq.pop();
cnt += a + b;
pq.push(a + b);
}
printf("%d\n", cnt);
}
return 0;
}