用STL水平衡树的题

vector

预备动作

#include <vector>
#include <algorithm>
using namespace std;

vector<int> tree;

插入数 (x)

tree.insert(lower_bound(tree.begin(), tree.end(), x), x);

删除数 (x) (若有多个相同的数,只删除一个)

tree.erase(lower_bound(tree.begin(), tree.end(), x));

查询 (x) 数的排名

res = lower_bound(tree.begin(), tree.end(), x) - tree.begin() + 1;

查询排名为 (x) 的数

res = tree[x - 1];

(x) 的前驱

res = *--lower_bound(tree.begin(), tree.end(), x);

(x) 的后继

res = *upper_bound(tree.begin(), tree.end(), x);

模板题完整代码

P3369 普通平衡树

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n;
    scanf("%d", &n);

    vector<int> tree;
    while (n--) {
        int op, x;
        scanf("%d %d", &op, &x);

        if (op == 1) tree.insert(lower_bound(tree.begin(), tree.end(), x), x);
        else if (op == 2) tree.erase(lower_bound(tree.begin(), tree.end(), x));
        else if (op == 3) printf("%d
", lower_bound(tree.begin(), tree.end(), x) - tree.begin() + 1);
        else if (op == 4) printf("%d
", tree[x - 1]);
        else if (op == 5) printf("%d
", *--lower_bound(tree.begin(), tree.end(), x));
        else printf("%d
", *upper_bound(tree.begin(), tree.end(), x));  
    }
    return 0;
}

洛谷测评(C++17 O2)总用时305ms,最大点80ms。

multiset

(To be continued)

原文地址:https://www.cnblogs.com/szdytom/p/stl-as-tree.html