C++优先队列STL(自学记录)

85 阅读1分钟

常见STL容器学习

算法基础模板:

#include<bits/stdc++.h>
#define endl '\n'
#define int long long
​
using namespace std;
​
void solve()
{
    // 解题
}
​
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin >> t; // 单测则注释
    while (t--)
        solve();
    return 0;
}

优先队列:

image-20240313144259672.png

image-20240313144519216.png

image-20240313144830270.png

image-20240313144944303.png

image-20240313145013176.png

image-20240313152045424.png

image-20240313152130218.png

image-20240313152325006.png

image-20240313152525176.png

定义比较条件

当你使用自己定义的结构体时,需要重载小于号,或者重载一下运算符

比如这里的node,不然不知道如何比较的.

使用的例子:

cmp函数

具体使用

基本操作:

例题

小e的菜篮子 - StarryCoding | 踏出编程第一步

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define endl '\n'
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  // define priority_queue
  priority_queue<ll> pq;
  ll sum = 0;  // the sum of the pq`s element;
​
  int q;
  cin >> q;
​
  while (q--) {
    int op;
    cin >> op;
    if (op == 1) {
      ll x;
      cin >> x;
      pq.push(x);
      sum += x;
    } else if (op == 2) {
      if (!pq.empty()) {
        ll x = pq.top();
        sum -= x;
        pq.pop();
      }
    }
  }
  cout << sum << endl;
  return 0;
}

image-20240313152755574.png

image-20240313203111521.png

image-20240313203202267.png

image-20240313203325151.png

image-20240313203649092.png

image-20240313203649092.png