NYOJ55懒省事的小明

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=55


这个题和石子合并有一定区别,这个是任意两堆都可以合并,所以贪心就好了,每次合并两堆重量最小的,优先队列!!


代码:


#include <cstdio>
#include <queue>

using namespace std;
typedef long long ll;

priority_queue<ll,vector<ll>,greater<ll> > pq;

void clear()

{
    while(!pq.empty())
        pq.pop();
}
int main()

{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        for(int i = 0;i < n;++i)
        {
            int a;
            scanf("%d",&a);
            pq.push(a);
        }
        ll ans = 0;
        int cnt = 1;
        while(cnt != n && !pq.empty())
        {
            ll x = pq.top();
            pq.pop();
            ll y = pq.top();
            pq.pop();
            ans += x + y;
            pq.push(x + y);
            ++cnt;
        }
        clear();
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(ACM,优先队列,贪心)