Welcome

首页 / 软件开发 / 数据结构与算法 / UVa 10954 Add All:哈弗曼树

UVa 10954 Add All:哈弗曼树2014-07-24

10954 - Add All

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=1895

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 of 11. If you want to add 1, 2 and 3. There are several ways –

纯练手。

完整代码:

/*0.035s*/#include<cstdio>#include<queue>#include<vector>#include<functional>using namespace std;typedef long long ll;priority_queue<ll, vector<ll>, greater<ll> > q;int main(){int n;ll x, sum;while (scanf("%d", &n), n){while (!q.empty()) q.pop();while (n--){scanf("%lld", &x);q.push(x);}sum = 0;while (true){x = q.top();q.pop();x += q.top();q.pop();sum += x;if (!q.empty()) q.push(x);else break;}printf("%lld
", sum);}return 0;}
作者署名:csdn博客 synapse7