zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    第十二周工作总结
    第八周工作总结
    冲刺2
    冲刺1
    用户场景分析
    用户场景分析
    水王在哪
    课堂练习-4个数的和
    《大道至简》第一章读后感
    ELF Format 笔记(三)—— Section Types
  • 原文地址:https://www.cnblogs.com/algorithms/p/2468103.html
Copyright © 2011-2022 走看看