2017ecjtu-summer training #4 UESTC 1599

题目链接   http://acm.uestc.edu.cn/#/problem/show/1599

题意   n个数 每次合并最小的两个数加到sum中,直到只剩一个数为止 常规解会超时,后来想到了用优先队列。

AC代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct cmp
{
    bool operator()(int a,int b)
    {
        return a>b;            //最小值优先
    }
};
priority_queue<ll,vector<ll>,cmp>p;
int n;
int main()
{
    cin>>n;
    int x;
    ll ans=0;
    for(int i=0;i<n;i++)
    {
        cin>>x;
        p.push(x);
    }
    while(p.size()>=2)
    {
        int p1=p.top();
        p.pop();
        int p2=p.top();
        p.pop();
        p1+=p2;
        p.push(p1);   //将最小的两个数的和返回到队列中
        ans+=p1;
    }
    cout<<ans<<endl;
}
原文地址:https://www.cnblogs.com/stranger-/p/7160566.html