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;
}
相關文章
- 8.13(優先佇列貪心維護+打表找規律+對頂堆優先佇列+DFS減枝+貪心dp)佇列
- CodeForces - 960B:Minimize the error(優先佇列+貪心)Error佇列
- Sunscreen POJ - 3614(防曬油) 貪心-優先佇列佇列
- [USACO 2009 Feb Gold] Fair Shuttle (貪心+優先佇列)GoAI佇列
- PHP優先佇列PHP佇列
- HDU - 6003 Problem Buyer題解(貪心選擇演算法,鴿巢原理,優先佇列維護)演算法佇列
- STL 優先佇列 用法佇列
- 堆與優先佇列佇列
- 淺談優先佇列佇列
- 優先佇列和堆排序佇列排序
- 01揹包優先佇列優化佇列優化
- 棧,佇列,優先順序佇列簡單介面使用佇列
- 佇列 優先順序佇列 python 程式碼實現佇列Python
- 優先佇列的比較器佇列
- 封裝優先順序佇列封裝佇列
- NO GAME NO LIFE(優先佇列/最小堆)GAM佇列
- 三、資料結構演算法-棧、佇列、優先佇列、雙端佇列資料結構演算法佇列
- leetcode621——優先佇列的思路LeetCode佇列
- STL優先佇列最小堆最大堆佇列
- 手擼優先佇列——二叉堆佇列
- C++ STL 優先佇列 (priority_queue)C++佇列
- .NET 6 優先佇列 PriorityQueue 實現分析佇列
- 二叉堆實現優先佇列佇列
- Java優先順序佇列DelayedWorkQueue原理分析Java佇列
- 演算法面試(三) 優先佇列演算法面試佇列
- 【堆】【優先佇列】[NOIP2004]合併果子佇列
- Facebook的分散式優先順序佇列FOQS分散式佇列
- 最詳細版圖解優先佇列(堆)圖解佇列
- 堆、堆排序和優先佇列的那些事排序佇列
- 【Dijkstra演算法】未優化版+優先佇列優化版演算法優化佇列
- codeforces round 974(div.3)E(優先佇列實現dijstra演算法,devc++的優先佇列用greater報錯)佇列JS演算法devC++
- Python3 執行緒優先順序佇列( Queue)Python執行緒佇列
- MaxHeap 最大堆 MinHeap 最小堆 PriorityQueue 優先佇列實現佇列
- CSP之公共鑰匙盒(模擬、排序、優先佇列)排序佇列
- 【力扣】最大子陣列和(貪心)力扣陣列
- 遞推,遞迴,貪心,列舉思想遞迴
- 貪心
- RMQ——支援合併和優先順序的訊息佇列MQ佇列
- 資料結構之PHP(最大堆)實現優先佇列資料結構PHP佇列