UVa 10954 - Add All

  题目大意:给出一些数,把他们相加,计算最小代价。

  很明显感觉是贪心,不过开始想错了,只是把他们排了一下序然后相加,想的太简单了。。。属于哈夫蔓树的模型吧,看别人的代码,新试了一下优先队列,还要好好看看优先队列的东西。

 1 #include <cstdio>
 2 #include <queue>
 3 using namespace std;
 4 
 5 struct Node
 6 {
 7     int x;
 8     bool operator < (const Node& a) const {
 9         return x > a.x;
10     }
11 };
12 
13 int main()
14 {
15 #ifdef LOCAL
16     freopen("in", "r", stdin);
17 #endif
18     int n;
19     while (scanf("%d", &n) != EOF && n)
20     {
21         Node t;
22         priority_queue<Node> q;
23         for (int i= 0; i < n; i++)
24         {
25             scanf("%d", &t.x);
26             q.push(t);
27         }
28         int ans = 0;
29         while (!q.empty())
30         {
31             Node t1 = q.top();
32             q.pop();
33             Node t2 = q.top();
34             q.pop();
35             ans += t1.x + t2.x;
36             t.x = t1.x + t2.x;
37             if (!q.empty())   q.push(t);
38         }
39         printf("%d\n", ans);
40     }
41     return 0;
42 }
View Code

 

posted @ 2013-08-12 14:55  xiaobaibuhei  阅读(162)  评论(0)    收藏  举报