priority queue在许多的特别场合还是很实用的,优先队列是依据堆(二叉树)实现的,效率是O(lgn),因为它带来的便利,人们可以少写很多的代码,所以学习它是有必要的。

很多时候我们会自己定义比较函数,因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系,所以如果用>在g++编译器中编译不过,在函数中operator旁边还是用<吧,或者使用()。使用”priority_queue<int,vector<int>,greater<int> >“类似的语句可以将大到小的默认顺序改成小到大(头文件是<functional>,我们也可以自己写一个比较类设定优先级。
struct cmp{
   bool operator()(type a,type b){
       return -------;
   }
};
 

#include<queue>
#include<iostream>
#include<functional>
#include<cmath>
#include<cstdio>
using namespace std;
struct cmp{
bool operator()(int a,int b){
return a>b; //想让其从小到大输出,return >
}
};
struct point{
int x,y;
void show(){
printf("(%d,%d)\n",x,y);
}
};
struct cmp2{
bool operator()(point a,point b){
return (abs(a.x)+abs(a.y))<(abs(b.x)+abs(b.y));
}
};
int main(){ //优先队列默认按照从大到小的顺序排列输出
freopen("cout.txt","w",stdout);
int a[5]={3,5,2,1,7};
priority_queue<int> v;
for( int i = 0; i < 5; i++ ) {
v.push(a[i]);
}
cout<<"v.size:"<<v.size()<<endl;
while( !v.empty() ) {
cout << v.top() << endl;
v.pop();
}
cout<<"v.size:"<<v.size()<<endl;
priority_queue<int,vector<int>,greater<int> > v2;
//priority_queue<int,vector<int>,less<int> > v; //less 降序 ,greater 升序

for( int i = 0; i < 5; i++ ) {
v2.push(a[i]);
}
cout<<"v2 从小到大输出:\n";
while( !v2.empty() ) {
cout << v2.top() << endl;
v2.pop();
}
priority_queue<int,vector<int>,cmp> v3;
for( int i = 0; i < 5; i++ ) {
v3.push(a[i]);
}
cout<<"自定义比较的V3输出:\n";
while( !v3.empty() ) {
cout << v3.top() << endl;
v3.pop();
}
cout<<"点输出优先级:与原点的曼哈顿距离。\n";
point p[5]={{0,9},{12,0},{3,4},{6,5},{3,7}};
priority_queue<point,vector<point>,cmp2> que;
//priority_queue<point> que; 复杂的类型需要写出专门的比较类(上面的cmp2)。
for(int i=0;i<5;i++)que.push(p[i]);
while( !que.empty() ) {
point tmp=que.top();
tmp.show();
que.pop();
}
return 0;
}


相关的结果:

v.size:5
7
5
3
2
1
v.size:0
v2 从小到大输出:
1
2
3
5
7
自定义比较的V3输出:
1
2
3
5
7
点输出优先级:与原点的曼哈顿距离。
(12,0)
(6,5)
(3,7)
(0,9)
(3,4)


一个应用例子:

nefu 355 合成陨石

​http://acm.nefu.edu.cn/JudgeOnline/problemshow.php?problem_id=355​

大意:一堆石子两两合并,合并的新石子加入原石堆中,每次合并产生的新石子质量是合并石子的质量和,且记录下来,请问最后的最小的质量和

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;

int main()
{
int n,a;
while(cin>>n){
priority_queue<int,vector<int>,greater<int> > que;
for(int i=0;i<n;i++) {
scanf("%d",&a);
que.push(a);
}
if(n==1) {
printf("%d\n",a);
continue;
}
int ans=0,get=0;
while(!que.empty()){
get=que.top();
que.pop();
if(que.empty()) break;
get=get+que.top();
que.pop();
ans=ans+get;
que.push(get);
}
printf("%d\n",ans);
}
return 0;
}