用priority_queue把輸入由小排到大,在queue剩一個資料之前,執行合併最小的兩個數字,累加至ans,接著再推入合併的值
4
10 11 12 13 //測資 答案為92 非100
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#define fast_as_a_fuckboy ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
int main(){
fast_as_a_fuckboy;
int num;
long long int n, ans;
while(cin >> n && n != 0){
priority_queue<long long,vector<long long>,greater<long long>> pq;
ans = 0;
for(int i = 0; i < n; i++){
cin >> num;
pq.push(num);
}
long long int sum;
while(pq.size() > 1){
long long int first = pq.top();
pq.pop();
long long int second = pq.top();
pq.pop();
sum = first + second;
ans += sum;
pq.push(sum);
}
cout << ans << "\n";
}
}