题意  求把全部数加起来的最小代价  a+b的代价为(a+b)

越先运算的数  要被加的次数越多  所以每次相加的两个数都应该是剩下序列中最小的数  然后结果要放到序列中  也就是优先队列了

#include<cstdio>
#include<queue>
using namespace std;
priority_queue<int, vector<int>, greater<int> >q;
typedef long long ll;
ll ans;
int main()
{
int n, t;
while(scanf("%d", &n), n)
{
for(int i = 0; i < n; ++i)
{
scanf("%d", &t);
q.push(t);
} ans = 0;
while(!q.empty())
{
int a = q.top(); q.pop();
int b = q.top(); q.pop();
ans += (a + b);
if(q.empty()) break;
q.push(a + b);
}
printf("%lld\n", ans);
}
return 0;
}

Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply question your erudition. So, let’s add some flavor of ingenuity
to it.

Addition operation requires cost now, and the cost is the summation of those two to be added. So, to add 1 and 10, you need a cost of11. If you want to add 12 and 3. There
are several ways –

1 + 2 = 3, cost = 3

3 + 3 = 6, cost = 6

Total = 9

1 + 3 = 4, cost = 4

2 + 4 = 6, cost = 6

Total = 10

2 + 3 = 5, cost = 5

1 + 5 = 6, cost = 6

Total = 11

I hope you have understood already your mission, to add a set of integers so that the cost is minimal.

Input

Each test case will start with a positive number, N (2 ≤ N ≤ 5000) followed by N positive integers (all are less than 100000). Input is terminated by a case where the value of N is zero.
This case should not be processed.

Output

For each case print the minimum total cost of addition in a single line.

Sample Input                           Output for Sample Input

3

1 2 3

4

1 2 3 4

0

 

9

19

 



最新文章

  1. 执行插入语句,object val = cmd.ExecuteScalar() val = null
  2. Redis学习笔记2-Redis的安装体验
  3. 3到6年的.NETer应该掌握哪些知识?
  4. Frost R&amp;D
  5. JAVA ,Map接口 ,迭代器Iterator
  6. 洛谷P2727 01串 Stringsobits
  7. 安全接口 interface --显示实现接口
  8. 「Windows MFC 」「Edit Control」 控件
  9. android仿京东、淘宝商品详情页上拉查看详情
  10. DRBD脑裂解决方法
  11. 重设mysql数据库root用户密码
  12. 聊聊java基础,int值强制类型转换成byte
  13. perl选项、特殊变量、一些函数参考手册
  14. Python网络爬虫:空姐网、糗百、xxx结果图与源码
  15. 100种不同图片切换效果插件pageSwitch
  16. JAVA 中的MessageDigest类和Mac类的使用
  17. git get submodule after clone
  18. python中的全局变量和局部变量(转)
  19. hdu 5831 Rikka with Parenthesis II 线段树
  20. bashrc profile的区别

热门文章

  1. python+opencv+Face++实现人脸识别比对
  2. 生成100个Div
  3. Python多线程爬图&amp;Scrapy框架爬图
  4. Android基础TOP7_1:ListView制作列表
  5. MS-DOS Batch Script Template
  6. mysqlbinlog flashback 使用最佳实践
  7. Android(java)学习笔记205:JNI之编写jni程序适配所有处理器型号
  8. jmeter元件的作用域和顺序
  9. 微信浏览器播放音频的问题:preload属性
  10. 解决[disabled]=&quot;true&quot;与formControlName冲突