优先队列的那些事

本文介绍了C++中优先队列的概念和使用方法,包括如何实现从大到小和从小到大的排序。通过示例代码展示了整数和结构体在优先队列中的排序过程,强调了重载'<'操作符的重要性。
摘要由CSDN通过智能技术生成

优先队列是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;
}

运行完长这样:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值