uva10954Add All(貪心+優先佇列)
題目連結:http://vjudge.net/contest/view.action?cid=50494#problem/D
Add All
Input: standard input
Output: standard output
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, lets 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 of 11. If you want to add 1, 2 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 |
程式碼如下:
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int main()
{
int n;
while(cin>>n,n){
int a;
priority_queue<long long, vector<long long>, greater<long long> >q;//從小到大
//過載優先順序,預設的是從大到小排列
for(int i=0;i<n;i++){
cin>>a;
q.push(a);
}
long long ans=0,x1,x2;
while(!q.empty()){
x1=q.top();
q.pop();//注意只剩一個元素的時候
if(q.empty())
break;
x2=q.top();
q.pop();
x1+=x2;
ans+=x1;
q.push(x1);
}
cout<<ans<<endl;
}
return 0;
}
相關文章
- HDU5630 Hiking(貪心+優先佇列)佇列
- Sunscreen POJ - 3614(防曬油) 貪心-優先佇列佇列
- CodeForces - 960B:Minimize the error(優先佇列+貪心)Error佇列
- [USACO 2009 Feb Gold] Fair Shuttle (貪心+優先佇列)GoAI佇列
- BZOJ 1572 [Usaco2009 Open]工作安排Job:貪心 + 優先佇列【先放再更新】佇列
- hdu5380 貪心+雙端佇列佇列
- Codeforces Round #390 (Div. 2)(A,B,C(記憶化搜尋),D(貪心,優先佇列))佇列
- PHP優先佇列PHP佇列
- 堆--優先佇列佇列
- 優先佇列 (轉)佇列
- BZOJ 1724 [Usaco2006 Nov]Fence Repair 切割木板:貪心 優先佇列【合併果子】AI佇列
- 淺談優先佇列佇列
- STL 優先佇列 用法佇列
- 堆與優先佇列佇列
- 堆和優先佇列佇列
- 優先佇列和堆排序佇列排序
- 堆排序與優先佇列排序佇列
- Java優先佇列(PriorityQueue)示例Java佇列
- BZOJ1029: [JSOI2007]建築搶修[模擬 貪心 優先佇列]JS佇列
- 01揹包優先佇列優化佇列優化
- 棧,佇列,優先順序佇列簡單介面使用佇列
- Redis實現任務佇列、優先順序佇列Redis佇列
- NO GAME NO LIFE(優先佇列/最小堆)GAM佇列
- 優先佇列的比較器佇列
- 封裝優先順序佇列封裝佇列
- 二叉堆優先佇列佇列
- POJ 3253 Fence Repair 優先佇列AI佇列
- 堆——神奇的優先佇列(上)佇列
- 優先佇列的效能測試佇列
- hdu5040 優先佇列+bfs佇列
- 佇列 優先順序佇列 python 程式碼實現佇列Python
- HDU - 6003 Problem Buyer題解(貪心選擇演算法,鴿巢原理,優先佇列維護)演算法佇列
- 演算法面試(三) 優先佇列演算法面試佇列
- STL優先佇列最小堆最大堆佇列
- STL醜數(set+優先佇列)佇列
- 【圖論】拓撲排序+優先佇列圖論排序佇列
- 1007(優先佇列)佇列
- POJ 1724 ROADS(優先佇列+spfa)佇列