UVA 10954 Add All

题意:

  给出n个数,要将n个数相加,每次相加所得的值为当次的计算量,完成所有的求和运算后,要求总的计算量最小。

分析:

  直接一个优先队列,由小到大排序,每次前两个相加就好。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<queue>
using namespace std;
struct cmp
{
bool operator() (int a,int b)
{
return a>b;
}
};
priority_queue<int,vector<int>,cmp>q;
int main()
{
int n;
while (scanf("%d",&n),n)
{
int i;
int x,y,sum;
for (i=1;i<=n;i++)
{
scanf("%d",&x);
q.push(x);
}
sum=0;
while (q.size()>1)
{
y=q.top();
q.pop();
y+=q.top();
q.pop();
sum+=y;
q.push(y);
}
q.pop();
printf("%d ",sum);
}
return 0;
}
原文地址:https://www.cnblogs.com/137033036-wjl/p/4953455.html