[ABC241D] Sequence Query 题解

· · 题解

思路

set

set 是一个 STL 里的关联式容器,其内部是平衡树(红黑树),维护一个有序集合。

下面介绍两种本题需要用到的 set 支持的操作。

  1. s.insert(x) 在集合 s 中插入一个元素 x。
  2. s.lower_bound(x) 在集合 s 中查找第一个大于等于 x 的元素的地址。

需要注意的几点

实现

复杂度证明

由于 set 内部是红黑树,其所有操作复杂度均为 O(\operatorname{log}n) 。

然后每次查询最多往前后查 k 个元素,而 k≤5 。

代码

#include <bits/stdc++.h>
using namespace std;

long long q , x, k, op;
multiset<long long> a;

int main() {
    cin >> q;

    while (q--) {
        op, x;
        cin >> op >> x; 
        if (op == 1)
            a.insert(x);
        else if (op == 2) {
            cin >> k;
            auto ans = a.upper_bound(x);

            while (ans != a.begin() && k)
                k--, ans--;

            if (k)
                cout << "-1\n";
            else
                cout << *ans << '\n';
        } else {
            cin >> k;
            auto ans = a.lower_bound(x);

            while (ans != a.end() && k > 1)
                k--, ans++;

            if (ans == a.end())
                cout << "-1\n";
            else
                cout << *ans << '\n';
        }
    }

    return 0;
}