priority_queue针对不同数据类型的使用方法
参考网站:https://blog.csdn.net/qq_19656301/article/details/82490601
https://blog.csdn.net/c20182030/article/details/70757660?locationNum=5&fps=1
非结构体优先队列
#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
#include <functional>
using namespace std;
priority_queue<int, vector<int>, greater<int> > q; //小顶堆
//priority_queue<int, vector<int>, less<int> > q; //大顶堆
//元素为int类型的优先队列 优先规则由greater以及less决定
int main(){
int n, x;
scanf("%d", &n);
for (int i = 1; i <= n; i++){
scanf("%d", &x);
q.push(x);
}
while (!q.empty()){ //队列顶端始终为符合优先规则的优先元素
printf("%d ", q.top());
q.pop();
}
return 0;
}
pair类型优先队列
#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
#include <utility>
#include <functional>
using namespace std;
typedef pair<int, int> info;
priority_queue<info, vector<info>, greater<info> > q; //小顶堆
//priority_queue<info, vector<info>, less<info> > q; //大顶堆
//元素为info类型的优先队列 优先规则由greater以及less决定
//pair的排序规则为首先比较第一个数值大小 如第一数值相等再比较第二个数值大小
int main(){
int n, x, y;
scanf("%d", &n);
for (int i = 1; i <= n; i++){
scanf("%d %d", &x, &y);
q.push(make_pair(x, y));
}
while (!q.empty()){ //队列顶端始终为符合优先规则的优先元素
printf("%d %d\n", q.top().first, q.top().second);
q.pop();
}
return 0;
}
结构体优先队列
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
struct node{
int x, y;
//重载 < 运算符 自定义结构体比较规则
bool operator < (const node &b) const{
return this->x > b.x; //小顶堆
//return this->x < b.x; //大顶堆
}
node(const int &x, const int &y){ //结构体初始化
this->x = x;
this->y = y;
}
};
priority_queue<node> q;
//元素为node类型的优先队列 优先规则由结构体重载运算符决定
int main(){
int n, x, y;
scanf("%d", &n);
for (int i = 1; i <= n; i++){
scanf("%d%d", &x, &y);
q.push(node(x, y));
}
while (!q.empty()){ //队列顶端始终为符合优先规则的优先元素
printf("%d %d\n", q.top().x, q.top().y);
q.pop();
}
node tmp1(3, 5);
node tmp2(4, 2);
//旨在说明 要注意这里的 < 不是小于号 而是一种比较规则
//默认采取小顶堆 则这里的 < 起到的作用是大于号
if (tmp1 < tmp2) printf("tmp1 > tmp2\n");
else printf("tmp1 < tmp2\n");
return 0;
}