1,定义及简述
对于这个模板类priority_queue,它是STL所提供的一个非常有效的容器。
作为队列的一个延伸,优先队列包含在头文件 <queue> 中。
优先队列时一种比较重要的数据结构,它是有二项队列编写而成的,可以以O(log n) 的效率查找一个队列中的最大值或者最小值,其中是最大值还是最小值是根据创建的优先队列的性质来决定的。
优先队列有三个参数,其声明形式为:
priority_queue< type, container, function >
这三个参数,后面两个可以省略,第一个不可以。
其中:
type:数据类型; container:实现优先队列的底层容器; function:元素之间的比较方式;
对于container,要求必须是数组形式实现的容器,例如vector、deque,而不能使list。
在STL中,默认情况下(不加后面两个参数)是以vector为容器,以 operator< 为比较方式,所以在只使用第一个参数时,优先队列默认是一个最大堆,每次输出的堆顶元素是此时堆中的最大元素。
2,成员函数
假设type类型为int,则:
bool empty() const // 返回值为true,说明队列为空; int size() const // 返回优先队列中元素的数量; void pop() // 删除队列顶部的元素,也即根节点 int top() // 返回队列中的顶部元素,但不删除该元素; void push(int arg) // 将元素arg插入到队列之中;
3,大顶堆与小顶堆
大顶堆:
//构造一个空的优先队列(此优先队列默认为大顶堆) priority_queue<int> big_heap; //另一种构建大顶堆的方法 priority_queue<int,vector<int>,less<int> > big_heap2;
小顶堆
//构造一个空的优先队列,此优先队列是一个小顶堆,即小的先出 priority_queue<int,vector<int>,greater<int> > small_heap;
需要注意的是,如果使用less<int>和greater<int>,需要头文件:
#include <functional>
4,代码示例
#include <iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int main()
{
long long int sum;
int i,n,t,a,b;
while(~scanf("%d",&n))
{
priority_queue<int,vector<int>,greater<int> >q;
for(i=0; i<n; i++)
{
scanf("%d",&t);
q.push(t);
}
sum=0;
if(q.size()==1)
{
a=q.top();
sum+=a;
q.pop();
}
while(q.size()>1)
{
a=q.top();
q.pop();
b=q.top();
q.pop();
t=a+b;
sum+=t;
q.push(t);
}
printf("%lld
",sum);
}
return 0;
}
部分参考:https://blog.csdn.net/lym940928/article/details/89635690