uva 10954——Add All

来源:互联网 发布:sql带参数的存储过程 编辑:程序博客网 时间:2024/06/06 07:19

<p>题意:给定一个序列,然后从中选择两个数,相加后放入原来的序列,消耗的费用为两个数 的和,问最小的代价。</p><p></p><p>思路:贪心。用优先队列维护,每次取得时候都取最小的两个即可。</p><p></p><p>code:</p>
#include <bits/stdc++.h>using namespace std;int main(){    int n,x;    while (~scanf("%d",&n)&&n)    {        priority_queue<int,vector<int>,greater<int> >q;        for (int i=0;i<n;i++)            scanf("%d",&x),q.push(x);        int ans=0;        for (int i=0;i<n-1;i++)        {            int a=q.top();q.pop();            int b=q.top();q.pop();            ans+=a+b;            q.push(a+b);        }        printf("%d\n",ans);    }}



0 0