POJ3253(Fence Repair)

题目链接

贪心题,也是训练优先队列的好题。

题目大意:给一块长木板,现要将其锯成n段,共需锯n-1次,每次锯的代价为所锯木板的长度,求最小总代价。

其实也可以看成是把n段木板拼成一块,每次拼的代价为所拼木板的长度和。这就跟哈夫曼编码一样,每次选取两个最小的来拼。具体实现时用优先队列。

View Code
 1 #include <stdio.h>
 2 #include <queue>
 3 using namespace std;
 4 #define INF 0x7fffffff
 5 priority_queue<int,vector<int>,greater<int> > pq;
 6 int main()
 7 {
 8   int n,i,l,a,b;
 9   long long ans;
10   while(~scanf("%d",&n))
11   {
12     for(i=0;i<n;i++)
13     {
14       scanf("%d",&l);
15       pq.push(l);
16     }
17     pq.push(INF);
18     ans=0;
19     while(!pq.empty())
20     {
21       a=pq.top(),pq.pop();
22       b=pq.top(),pq.pop();
23       if(b==INF)  break;
24       ans+=a;
25       ans+=b;
26       pq.push(a+b);
27     }
28     while(!pq.empty()) pq.pop();
29     printf("%lld\n",ans);
30   }
31   return 0;
32 }

 

posted @ 2012-04-24 15:05  BeatLJ  阅读(741)  评论(0编辑  收藏  举报