abc217E 带排序的查询

49 阅读1分钟

题面:初始时有空序列A,接下来有Q组操作,每个操作的格式如下:

  • 1 x,将x追加到A的末尾。
  • 2,输出A开头的元素值,并移除。请求时保证A非空。
  • 3,对A中元素从小到大排序。

范围:1 <= Q <= 2E5; 0 <= x <= 1E9

分析:用一个队列来维护还没有排序的元素,再用一个优先队列来维护已排序的元素。由于每次只能追加到末尾,优先队列里的元素一定在队列的前面。

#include <bits/stdc++.h>
void solve() {
    int Q;
    std::cin >> Q;
    std::queue<int> q;
    std::priority_queue<int> pq;
    while (Q--) {
        int op, x;
        std::cin >> op;
        if (op == 1) {
            std::cin >> x;
            q.push(x);
        } else if (op == 2) {
            if (pq.empty()) {
                std::cout << q.front() << "\n";
                q.pop();
            } else {
                std::cout << -pq.top() << "\n";
                pq.pop();
            }
        } else {
            while (!q.empty()) {
                pq.push(-q.front());
                q.pop();
            }
        }
    }
}
int main() {
    std::cin.tie(0)->sync_with_stdio(0);
    int t = 1;
    while (t--) solve();
    return 0;
}

标签:思维