Files
python/GESP/Level5/GESP202412/20241202.md
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

43 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 一、 前导知识
#### 优先队列重载小于号
``` cpp
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
// 自定义排序方法1
// bool operator<(const Node &b) const {
// return val < b.val;
// }
// 自定义排序方法2
// 重载小于号,如果a.val<b.val,则返回true,也就是a比b小,但是,由于优先队列是大顶堆,大的先出,所以b先出队列
friend bool operator<(Node a, Node b) {
return a.val < b.val;
}
};
priority_queue<Node> q;
int main() {
Node a;
a.val = 1;
q.push(a);
Node b;
b.val = 2;
q.push(b);
cout << q.top().val << endl;
// 输出结果:2
// 解释:由于优先队列是大顶堆,所以大的先出,所以b先出队列
// 加快读入
return 0;
}
```
在此处定义一个优先队列**大顶堆**:`priority_queue pri`;
如果要按照以$val$的值进行 **从小到大** 排列,操作如上。重载$<$操作符。
意思是如果$a.val < b.val$成立,那么结构体`Node a < Node b`。
**解释**:由于优先队列大顶堆是按照从大到小排列,所以结构体$b$会排列到$a$之前。