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\n",sum); } return 0; }
部分參考:https://blog.csdn.net/lym940928/article/details/89635690