題目連結: https://zerojudge.tw/ShowProblem?problemid=b151
# 解題思路
運用 priority_queue 將數據排序好,之後再取最前面兩個合併再丟入,直到只剩一個解,就是答案啦!!
# 程式碼
#include <bits/stdc++.h> | |
using namespace std; | |
int main() { | |
priority_queue<int, deque<int>, greater<int> > pq; | |
int n; | |
while(cin>>n){ | |
int sum=0; | |
for(int i=0;i<n;i++){ | |
int num; | |
cin>>num; | |
pq.push(num); | |
} | |
while(pq.size()>1){ | |
int a,b; | |
a=pq.top(); | |
pq.pop(); | |
b=pq.top(); | |
pq.pop(); | |
pq.push(a+b); | |
sum+=a+b; | |
} | |
cout<<sum<<endl; | |
} | |
return 0; | |
} |