您的位置:首页 > 编程语言 > C语言/C++

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

2014-07-14 21:51 936 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: