例题8-11 10954 - Add All全部相加

很简单一道题目。

大体思路就是建立一个优先队列,数值小的优先级大,每次取出后,sum += a + b,总共操作n-1次!

#include<cstdio>
#include<queue>
using namespace std;
typedef long long ll;
int main()
{
    ll k,n;
    while(scanf("%lld",&n) == 1 && n){
        priority_queue<ll,vector<ll>,greater<ll> >pq;
        for (int i = 0; i < n; ++i){scanf("%lld",&k);pq.push(k);}
        ll sum = 0;
        while(pq.size() > 1){
            ll a = pq.top();pq.pop();
            ll b = pq.top();pq.pop();
            sum += a + b;
            pq.push(a+b);
        }
        printf("%lld\n",sum);
    }
    return 0;
}


你可能感兴趣的:(C语言,uva)