poj3253 Fence Repair 优先队列,C++STL中priority_queue的使用

2 篇文章 0 订阅
1 篇文章 0 订阅

题目链接:http://poj.org/problem?id=3253

题目大意:有一个农夫要把一个木板钜成几块给定长度的小木板,每次锯都要收取一定费用,这个费用就是当前锯的这个木版的长度
                    给定各个要求的小木板的长度,及小木板的个数n,求最小费用

思路:使用这些木板的长度构造一棵哈夫曼树,哈夫曼树中所有非叶子节点的值之和就是要求的最小费用。

        之所以找到道题,是想练习优先队列的使用,因为在dijkstra和一些其他的算法中需要使用优先队列。本以为在ACM中使用优先队列要自己写小根堆,结果发现STL中有实现好的priority_queue,据说效率也不错。懒得自己学着写优先队列了,以后就用priority_queue吧。这里给出一个介绍priority_queue的使用方法的博客:http://blog.chinaunix.net/uid-533684-id-2100009.html

///2014.7.14
///poj3253

//Accepted  908K    16MS    G++ 783B    2014-07-14 21:38:49

//优先队列,priority_queue用法练习

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

int n;
priority_queue<int,vector<int>,greater<int> > pque;
long long sum;

void init(){
    // pque.clean();
    scanf("%d",&n);
    int temp;
    for(int i=0 ; i<n ; i++){
        scanf("%d",&temp);
        pque.push(temp);
    }
    sum = 0;
}
void work(){
    long long a,b;
    while( pque.size()>1 ){
        a = pque.top(),pque.pop();
        b = pque.top(),pque.pop();
        sum += a + b;
        pque.push( a+b );
    }
}
int main(){
    // freopen("in","r",stdin);
    // freopen("out","w",stdout);

    init();
    work();
    cout<<sum<<endl;
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值