优先队列是STL提供的爽歪歪的排序方法,普通的队列是一种先进先出的数据结构(FIFO),元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出的行为特征。时间复杂度为O(logn)
比如对一大坨整数排序,可以想象成将这些数字一个一个,像给弹夹上子弹一样压进去,然后这个弹夹比较牛X,默认情况会将这些子弹从大到小排序,开枪时候先射出的就是大的子弹。
第一、整数从大到小
如下:
#include<iostream>
#include<queue>
using namespace std;
/*
O(logn)
6
4 8 2 9 5 7
*/
//默认从大到小排序
priority_queue<int> q1;
int main()
{
int n;
cin>>n;
int t;
for(int i=1;i<=n;i++)
{
cin>>t;
//一个一个压进弹夹
q1.push(t);
}
while(!q1.empty())
{
//一发一发射出
cout<<q1.top()<<" ";
q1.pop();
}
return 0;
}
执行完就是介个样纸的:
第二、整数从小到大
如果想对数字从小到大排序,则需要给这个弹夹加点料,声明优先队列时候就有修改为:
//注意:从小到大排序,最后两个> >中间必须要用空格
priority_queue<int,vector<int>,greater<int> >q1;
代码如下:
#include<iostream>
#include<queue>
/*
6
4 8 2 9 5 7
*/
using namespace std;
//从小到大排序,最后两个> >中间必须要用空格
priority_queue<int,vector<int>,greater<int> >q1;
int main()
{
int n;
cin>>n;
int t;
for(int i=1;i<=n;i++)
{
cin>>t;
q1.push(t);
}
while(!q1.empty())
{
cout<<q1.top()<<" ";
q1.pop();
}
return 0;
}
第三、结构体从大到小
接下来,假设要往优先队列里面放的不是整数,而是结构体,则需要重载下结构体的'<'比较方法,即重载operator <函数;
要实现结构体从大到小排序,代码如下:
#include <iostream>
#include <queue>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Node{
int x, y;
//结构体构造函数,为了创建结构体时候省力些
Node(int a, int b){
x=a;
y=b;
}
};
//a的优先级要比b的低,
//那么当x值相等时候,则a比b低需满足 a的y小于b的y
//当x不相等的时候,a比b低需满足 a的小大于b的x
bool operator < (Node a, Node b){
if( a.x== b.x ) return a.y< b.y;
return a.x< b.x;
}
int main(){
priority_queue<Node> q;
srand((unsigned) time(0));
for( int i= 0; i< 10; ++i ){
q.push( Node( rand()%100 , rand()%100 ) );
}
while( !q.empty() ){
cout << q.top().x <<" "<< q.top().y << endl;
q.pop();
}
return 0;
}
执行完是介个样纸的:
第四、结构体从小到大
最后,如果结构体要从小到大排序输出,则将重载'<'方法修改下就好:
代码:
#include <iostream>
#include <queue>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Node{
int x, y;
Node(int a, int b){
x=a;
y=b;
}
};
//a的优先级要比b的低,
//那么当x值相等时候,则a比b低需满足 a的y大于b的y
//当x不相等的时候,a比b低需满足 a的x大于b的x
bool operator < (Node a, Node b){
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}
int main(){
priority_queue<Node> q;
srand((unsigned) time(0));
for( int i= 0; i< 10; ++i ){
q.push( Node( 2, rand()%100 ) );
}
while( !q.empty() ){
cout << q.top().x <<" "<< q.top().y << endl;
q.pop();
}
return 0;
}
运行完长这样: