优先队列的分类
- 大根堆或大顶堆(队头元素保持最大,默认)
- 小根堆或小顶堆(队头元素保持最小)
使用的场景以及时间复杂度
优先队列用第三个参数来指定排序规则(参考下面代码),队列内部不是完全有序的,它只可以保证队头元素一直是最大或最小的。优先队列一般用于需要不停地从一堆元素中取走最大或最小的元素的场景。优先队列的效率较高,从其中删除元素、向其中插入元素的时间复杂度都是O(logn)
。
优先队列的基本操作(存储与遍历)
需要注意的是,大顶堆默认使用的是less
比较器,而不是greater
比较器
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> q1;//大根堆(写法一)
priority_queue<int,vector<int>,less<int>> q2;//大根堆(写法二,三个参数)
priority_queue<int,vector<int>,greater<int>> q3;//小根堆
q1.push(10); q1.push(8); q1.push(6); q1.push(4); q1.push(2);//加入元素
q2.push(10); q2.push(8); q2.push(6); q2.push(4); q2.push(2);
q3.push(10); q3.push(8); q3.push(6); q3.push(4); q3.push(2);
while (!q1.empty())//队列非空,输出队首(堆顶)元素
{
cout << q1.top() << " ";
q1.pop();
}
cout << endl;
while (!q2.empty())
{
cout << q2.top() << " ";
q2.pop();
}
cout << endl;
while (!q3.empty())
{
cout << q3.top() << " ";
q3.pop();
}
cout << endl;
return 0;
}
优先队列与结构体
期末考试之后,老师要求你写一个程序,将分数高的学生排在前面,如果两个学生分数相同,那么按照学号从大到小排序。如何利用优先队列实现呢?
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
struct student
{
int num;//学号
string name;//姓名
int score;//分数
//优先队列中大根堆默认使用的是less比较器,所以需要重载小于号
bool operator < (const student & s) const
{
//如果分数不同,按照分数从大到小排序;如果分数相同,按照学号从大到小排序
//结构体的分数小于当前队列中的;结构体与当前队列中分数相等,但学号小于队列中的学号;
if ((score < s.score) || (score == s.score && num < s.num)) return true;
else return false;
}
};
int main()
{
priority_queue<student,vector<student>,less<student> > q;//使用大根堆
student s1 = {1001,"zhang",100};
student s2 = {1004,"wang",98};
student s3 = {1002,"zhao",98};
student s4 = {1003,"huang",95};
q.push(s1); q.push(s2); q.push(s3); q.push(s4);
while (!q.empty())//队列非空,输出元素
{
cout << (q.top()).num << " " << (q.top()).name << " " << (q.top()).score;
cout << endl;
q.pop();
}
return 0;
}
输出如下:
1001 zhang 100
1004 wang 98
1002 zhao 98
1003 huang 95