【Huffman树贪心+优先队列】POJ3253-Fence Repair

思路详见之前的贪心专题,用优先队列来代替之前的插入排序,效率为O(nlogn)

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 using namespace std;
 5 const int MAXN=20000+5;
 6 int l[MAXN];
 7 
 8 int main()
 9 {
10     int n;
11     long long ans=0;
12     priority_queue<int,vector<int>,greater<int> > pque;//C++总是把两个连续的>看作右移位运算符,因此会导致错误,要加空格 
13     scanf("%d",&n);
14     for (int i=0;i<n;i++)
15     {
16         scanf("%d",&l[i]);
17         pque.push(l[i]);
18     }
19     while (pque.size()>1)
20     {
21         int a=pque.top();pque.pop();
22         int b=pque.top();pque.pop();
23         ans+=a+b;
24         pque.push(a+b);
25     }
26     cout<<ans<<endl;
27     return 0;
28 }
posted @ 2015-07-14 11:20  iiyiyi  阅读(180)  评论(0编辑  收藏  举报