m1une's library

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:heavy_check_mark: verify/ds/bst/persistent_ordered_set.test.cpp

Depends on

Code

#define PROBLEM "https://judge.yosupo.jp/problem/ordered_set"

#include "../../../ds/bst/persistent_ordered_set.hpp"

#include <cassert>
#include "../../../utilities/fast_io.hpp"

int main() {
    m1une::utilities::FastInput fast_input;
    m1une::utilities::FastOutput fast_output;

    m1une::ds::PersistentOrderedSet<int> pointer_test = {1, 3, 5};
    const int* stable_pointer = pointer_test.lower_bound(3);
    auto pointer_test_next = pointer_test;
    for (int x = 10; x < 1000; x++) pointer_test_next = pointer_test_next.insert(x);
    assert(stable_pointer && *stable_pointer == 3);
    auto [small, large] = pointer_test_next.split(500);
    auto joined = small.merge(large);
    assert(pointer_test_next.size() == joined.size());
    assert(pointer_test_next.to_vector() == joined.to_vector());

    int N, Q;
    fast_input >> N >> Q;

    m1une::ds::PersistentOrderedSet<int> st;
    for (int i = 0; i < N; i++) {
        int a;
        fast_input >> a;
        st = st.insert(a);
    }

    while (Q--) {
        int type, x;
        fast_input >> type >> x;

        if (type == 0) {
            st = st.insert(x);
        } else if (type == 1) {
            st = st.erase(x);
        } else if (type == 2) {
            if (st.size() < x) {
                fast_output << -1 << '\n';
            } else {
                fast_output << st.kth(x - 1) << '\n';
            }
        } else if (type == 3) {
            fast_output << st.count_less_equal(x) << '\n';
        } else if (type == 4) {
            const int* ans = st.max_le(x);
            fast_output << (ans ? *ans : -1) << '\n';
        } else {
            const int* ans = st.min_ge(x);
            fast_output << (ans ? *ans : -1) << '\n';
        }
    }
}
#line 1 "verify/ds/bst/persistent_ordered_set.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/ordered_set"

#line 1 "ds/bst/persistent_ordered_set.hpp"



#include <cstddef>
#include <functional>
#include <initializer_list>
#include <utility>
#include <vector>

#line 1 "ds/bst/persistent_ordered_multiset.hpp"



#include <cassert>
#line 10 "ds/bst/persistent_ordered_multiset.hpp"

#line 1 "ds/detail/persistent_binary_node_pool.hpp"



#line 6 "ds/detail/persistent_binary_node_pool.hpp"
#include <deque>
#include <limits>
#include <optional>
#line 11 "ds/detail/persistent_binary_node_pool.hpp"

namespace m1une {
namespace ds {
namespace detail {

// Node must have integer `l` and `r` members. New nodes initially have no
// owner; discard_unreferenced() removes temporary path-copy nodes after the
// result roots have been retained.
template <class Node, int null_node = -1>
struct PersistentBinaryNodePool {
   private:
    std::deque<std::optional<Node>> _nodes;
    std::vector<int> _references;
    std::vector<int> _next_free;
    std::vector<int> _unowned;
    int _first_free = -1;
    std::size_t _live_nodes = 0;

    void release_zero(int node) {
        assert(node != null_node && _nodes[node].has_value());
        int left = (*_nodes[node]).l;
        int right = (*_nodes[node]).r;
        _nodes[node].reset();
        _next_free[node] = _first_free;
        _first_free = node;
        --_live_nodes;
        if (left != null_node && --_references[left] == 0) release_zero(left);
        if (right != null_node && --_references[right] == 0) release_zero(right);
    }

   public:
    PersistentBinaryNodePool() {
        if constexpr (null_node == 0) {
            _nodes.emplace_back();
            _references.push_back(0);
            _next_free.push_back(-1);
        }
    }

    Node& operator[](int node) {
        assert(node != null_node && _nodes[node].has_value());
        return *_nodes[node];
    }

    const Node& operator[](int node) const {
        assert(node != null_node && _nodes[node].has_value());
        return *_nodes[node];
    }

    template <class... Args>
    int emplace(Args&&... args) {
        int result;
        if (_first_free == -1) {
            assert(_nodes.size() < std::size_t(std::numeric_limits<int>::max()));
            result = int(_nodes.size());
            _nodes.emplace_back(std::in_place, std::forward<Args>(args)...);
            _references.push_back(0);
            _next_free.push_back(-1);
        } else {
            result = _first_free;
            _first_free = _next_free[result];
            _nodes[result].emplace(std::forward<Args>(args)...);
            _references[result] = 0;
        }
        retain((*_nodes[result]).l);
        retain((*_nodes[result]).r);
        _unowned.push_back(result);
        ++_live_nodes;
        return result;
    }

    void retain(int node) {
        if (node != null_node) {
            assert(_nodes[node].has_value());
            ++_references[node];
        }
    }

    void release(int node) {
        if (node == null_node) return;
        assert(_nodes[node].has_value() && _references[node] > 0);
        if (--_references[node] == 0) release_zero(node);
    }

    bool unique(int node) const {
        return node == null_node || _references[node] == 1;
    }

    int clone(int node) {
        assert(node != null_node && _nodes[node].has_value());
        return emplace(*_nodes[node]);
    }

    // Returns node itself when it has one owner, otherwise an unowned clone.
    // A returned clone becomes owned when a root or parent edge retains it.
    int clone_if_shared(int node) {
        if (unique(node)) return node;
        return clone(node);
    }

    void replace(int& edge, int node) {
        if (edge == node) return;
        retain(node);
        int old = edge;
        edge = node;
        release(old);
    }

    void discard_unreferenced() {
        while (!_unowned.empty()) {
            int node = _unowned.back();
            _unowned.pop_back();
            if (_nodes[node].has_value() && _references[node] == 0) release_zero(node);
        }
    }

    void reserve(std::size_t) {}

    int next_index() const { return _first_free == -1 ? int(_nodes.size()) : _first_free; }

    std::size_t size() const { return _live_nodes; }
};

}  // namespace detail
}  // namespace ds
}  // namespace m1une


#line 12 "ds/bst/persistent_ordered_multiset.hpp"

namespace m1une {
namespace ds {

template <typename T, typename Compare>
struct PersistentOrderedSet;

template <typename T, typename Compare = std::less<T>>
struct PersistentOrderedMultiset {
   private:
    friend struct PersistentOrderedSet<T, Compare>;
    struct Node {
        T key;
        int count;
        int size;
        int distinct_size;
        int rank_color;
        int l;
        int r;
        int min_leaf;
        int max_leaf;

        Node(T value, int multiplicity, int maximum)
            : key(std::move(value)),
              count(multiplicity),
              size(multiplicity),
              distinct_size(1),
              rank_color(1),
              l(-1),
              r(-1),
              min_leaf(maximum),
              max_leaf(maximum) {}

        Node(T separator, int subtree_size, int left_size, int unique_count, int node_rank,
             int left, int right, int minimum, int maximum, bool is_black)
            : key(std::move(separator)),
              count(left_size),
              size(subtree_size),
              distinct_size(unique_count),
              rank_color(node_rank * 2 + int(is_black)),
              l(left),
              r(right),
              min_leaf(minimum),
              max_leaf(maximum) {}
    };

    using Pool = detail::PersistentBinaryNodePool<Node>;

    inline static Pool pool;

    int root;
    Compare comp;

    static int subtree_size(int t) { return t == -1 ? 0 : pool[t].size; }
    static int subtree_distinct_size(int t) { return t == -1 ? 0 : pool[t].distinct_size; }
    static int node_rank(int t) { return pool[t].rank_color >> 1; }
    static bool is_black(int t) { return (pool[t].rank_color & 1) != 0; }
    static bool is_leaf(int t) { return pool[t].l == -1; }

    bool equal(const T& a, const T& b) const {
        return !comp(a, b) && !comp(b, a);
    }

    static int make_leaf(T key, int count) {
        const int id = pool.next_index();
        return pool.emplace(std::move(key), count, id);
    }

    static int make_node(int l, int r, bool black) {
        assert(l != -1 && r != -1);
        const int rank = node_rank(l) + int(is_black(l));
        assert(rank == node_rank(r) + int(is_black(r)));
        return pool.emplace(pool[pool[l].max_leaf].key,
                            subtree_size(l) + subtree_size(r),
                            subtree_size(l),
                            subtree_distinct_size(l) + subtree_distinct_size(r),
                            rank, l, r, pool[l].min_leaf, pool[r].max_leaf,
                            black);
    }

    static int as_root(int t) {
        if (t == -1 || is_black(t)) return t;
        return make_node(pool[t].l, pool[t].r, true);
    }

    static int merge_sub(int a, int b) {
        assert(a != -1 && b != -1);
        if (node_rank(a) < node_rank(b)) {
            const Node& right = pool[b];
            int c = merge_sub(a, right.l);
            if (is_black(b) && !is_black(c) && !is_black(pool[c].l)) {
                const Node& middle = pool[c];
                if (is_black(right.r)) {
                    return make_node(middle.l,
                                     make_node(middle.r, right.r, false),
                                     true);
                }
                const Node& far = pool[right.r];
                return make_node(make_node(middle.l, middle.r, true),
                                 make_node(far.l, far.r, true),
                                 false);
            }
            return make_node(c, right.r, is_black(b));
        }
        if (node_rank(a) > node_rank(b)) {
            const Node& left = pool[a];
            int c = merge_sub(left.r, b);
            if (is_black(a) && !is_black(c) && !is_black(pool[c].r)) {
                const Node& middle = pool[c];
                if (is_black(left.l)) {
                    return make_node(make_node(left.l, middle.l, false),
                                     middle.r, true);
                }
                const Node& far = pool[left.l];
                return make_node(make_node(far.l, far.r, true),
                                 make_node(middle.l, middle.r, true),
                                 false);
            }
            return make_node(left.l, c, is_black(a));
        }
        return make_node(a, b, false);
    }

    static int merge_nodes(int a, int b) {
        if (a == -1 || b == -1) return a == -1 ? b : a;
        return as_root(merge_sub(as_root(a), as_root(b)));
    }

    std::pair<int, int> split_nodes(int t, const T& key) const {
        if (t == -1) return {-1, -1};
        const Node& node = pool[t];
        if (is_leaf(t)) return comp(node.key, key) ? std::pair{t, -1} : std::pair{-1, t};
        if (comp(node.key, key)) {
            auto [l, r] = split_nodes(node.r, key);
            return {merge_nodes(as_root(node.l), l), r};
        }
        auto [l, r] = split_nodes(node.l, key);
        return {l, merge_nodes(r, as_root(node.r))};
    }

    int change_count_impl(int t, const T& key, int delta, int& old_count) const {
        if (t == -1) return -1;
        const Node& node = pool[t];
        if (is_leaf(t)) {
            if (!equal(node.key, key)) return t;
            old_count = node.count;
            return node.count + delta == 0 ? t : make_leaf(node.key, node.count + delta);
        }
        int child;
        if (!comp(node.key, key)) {
            child = change_count_impl(node.l, key, delta, old_count);
            if (old_count == 0 || old_count + delta == 0) return t;
            return make_node(child, node.r, is_black(t));
        }
        child = change_count_impl(node.r, key, delta, old_count);
        if (old_count == 0 || old_count + delta == 0) return t;
        return make_node(node.l, child, is_black(t));
    }

    int change_count_inplace(int t, const T& key, int delta) const {
        t = pool.clone_if_shared(t);
        if (is_leaf(t)) {
            assert(equal(pool[t].key, key));
            assert(pool[t].count + delta > 0);
            pool[t].count += delta;
            pool[t].size += delta;
            return t;
        }
        if (!comp(pool[t].key, key)) {
            int child = change_count_inplace(pool[t].l, key, delta);
            pool.replace(pool[t].l, child);
        } else {
            int child = change_count_inplace(pool[t].r, key, delta);
            pool.replace(pool[t].r, child);
        }
        Node& node = pool[t];
        node.count = subtree_size(node.l);
        node.size = node.count + subtree_size(node.r);
        return t;
    }

    int count_impl(int t, const T& key) const {
        if (t == -1) return 0;
        while (!is_leaf(t)) {
            t = !comp(pool[t].key, key) ? pool[t].l : pool[t].r;
        }
        return equal(pool[t].key, key) ? pool[t].count : 0;
    }

    const T* kth_impl(int t, int k) const {
        while (!is_leaf(t)) {
            const int left_size = pool[t].count;
            if (k < left_size) {
                t = pool[t].l;
            } else {
                k -= left_size;
                t = pool[t].r;
            }
        }
        return &pool[t].key;
    }

    int order_of_key_impl(int t, const T& key, bool upper) const {
        int result = 0;
        while (t != -1 && !is_leaf(t)) {
            const Node& node = pool[t];
            const T& separator = node.key;
            const bool take_left = upper ? !comp(key, separator) : comp(separator, key);
            if (take_left) {
                result += node.count;
                t = node.r;
            } else {
                t = node.l;
            }
        }
        if (t != -1) {
            const bool take_leaf = upper ? !comp(key, pool[t].key) : comp(pool[t].key, key);
            if (take_leaf) result += pool[t].count;
        }
        return result;
    }

    const T* lower_bound_impl(int t, const T& key, bool strict) const {
        const T* result = nullptr;
        while (t != -1) {
            const Node& node = pool[t];
            if (is_leaf(t)) {
                const bool candidate = strict ? comp(key, node.key) : !comp(node.key, key);
                return candidate ? &node.key : result;
            }
            const T& separator = node.key;
            const bool go_left = strict ? comp(key, separator) : !comp(separator, key);
            if (go_left) {
                result = &pool[pool[node.r].min_leaf].key;
                t = node.l;
            } else {
                t = node.r;
            }
        }
        return result;
    }

    const T* max_less_impl(int t, const T& key, bool strict) const {
        const T* result = nullptr;
        while (t != -1) {
            const Node& node = pool[t];
            if (is_leaf(t)) {
                const bool candidate = strict ? comp(node.key, key) : !comp(key, node.key);
                return candidate ? &node.key : result;
            }
            const T& separator = node.key;
            const bool take_left = strict ? comp(separator, key) : !comp(key, separator);
            if (take_left) {
                result = &separator;
                t = node.r;
            } else {
                t = node.l;
            }
        }
        return result;
    }

    static void dump_impl(int t, std::vector<T>& result) {
        if (t == -1) return;
        const Node& node = pool[t];
        if (is_leaf(t)) {
            for (int i = 0; i < node.count; ++i) result.push_back(node.key);
            return;
        }
        dump_impl(node.l, result);
        dump_impl(node.r, result);
    }

    static std::pair<int, int> pop_min(int t) {
        assert(t != -1);
        const Node& node = pool[t];
        if (is_leaf(t)) return {t, -1};
        auto [minimum, rest] = pop_min(node.l);
        return {minimum, merge_nodes(rest, as_root(node.r))};
    }

    PersistentOrderedMultiset(int node, Compare compare) : root(node), comp(std::move(compare)) {
        pool.retain(root);
    }

    PersistentOrderedMultiset make_version(int node) const {
        PersistentOrderedMultiset result(node, comp);
        pool.discard_unreferenced();
        return result;
    }

   public:
    explicit PersistentOrderedMultiset(Compare compare) : root(-1), comp(std::move(compare)) {}
    PersistentOrderedMultiset() : PersistentOrderedMultiset(Compare()) {}

    PersistentOrderedMultiset(std::initializer_list<T> init, Compare compare = Compare())
        : PersistentOrderedMultiset(std::move(compare)) {
        for (const T& x : init) *this = insert(x);
    }

    template <typename Iterator>
    PersistentOrderedMultiset(Iterator first, Iterator last, Compare compare = Compare())
        : PersistentOrderedMultiset(std::move(compare)) {
        while (first != last) *this = insert(*first++);
    }

    PersistentOrderedMultiset(const PersistentOrderedMultiset& other)
        : root(other.root), comp(other.comp) {
        pool.retain(root);
    }

    PersistentOrderedMultiset(PersistentOrderedMultiset&& other)
        : root(other.root), comp(std::move(other.comp)) {
        other.root = -1;
    }

    PersistentOrderedMultiset& operator=(const PersistentOrderedMultiset& other) {
        if (this == &other) return *this;
        pool.retain(other.root);
        pool.release(root);
        root = other.root;
        comp = other.comp;
        return *this;
    }

    PersistentOrderedMultiset& operator=(PersistentOrderedMultiset&& other) {
        if (this == &other) return *this;
        pool.release(root);
        root = other.root;
        comp = std::move(other.comp);
        other.root = -1;
        return *this;
    }

    ~PersistentOrderedMultiset() { pool.release(root); }

    int size() const { return subtree_size(root); }
    int unique_size() const { return subtree_distinct_size(root); }
    bool empty() const { return root == -1; }
    void release() { pool.release(std::exchange(root, -1)); }
    std::size_t node_count() const { return pool.size(); }
    PersistentOrderedMultiset clear() const { return make_version(-1); }

    PersistentOrderedMultiset insert(T key, int multiplicity = 1) const {
        assert(multiplicity > 0);
        int old_count = 0;
        const int changed_root = change_count_impl(root, key, multiplicity, old_count);
        if (old_count != 0) {
            return make_version(changed_root);
        }
        auto [l, r] = split_nodes(root, key);
        return make_version(merge_nodes(merge_nodes(l, make_leaf(std::move(key), multiplicity)), r));
    }

    void insert_inplace(T key, int multiplicity = 1) {
        assert(multiplicity > 0);
        if (!contains(key)) {
            *this = insert(std::move(key), multiplicity);
            return;
        }
        int next_root = change_count_inplace(root, key, multiplicity);
        pool.replace(root, next_root);
        pool.discard_unreferenced();
    }

   private:
    PersistentOrderedMultiset insert_unique(T key) const {
        if (contains(key)) return *this;
        auto [l, r] = split_nodes(root, key);
        return make_version(merge_nodes(merge_nodes(l, make_leaf(std::move(key), 1)), r));
    }

   public:
    PersistentOrderedMultiset erase_one(const T& key) const {
        int old_count = 0;
        const int changed_root = change_count_impl(root, key, -1, old_count);
        if (old_count == 0) return *this;
        if (old_count > 1) return make_version(changed_root);
        auto [l, r] = split_nodes(root, key);
        auto [discarded, rest] = pop_min(r);
        assert(equal(pool[discarded].key, key));
        return make_version(merge_nodes(l, rest));
    }

    PersistentOrderedMultiset erase(const T& key) const { return erase_one(key); }

    bool erase_one_inplace(const T& key) {
        int old_count = count(key);
        if (old_count == 0) return false;
        if (old_count == 1) {
            *this = erase_one(key);
            return true;
        }
        int next_root = change_count_inplace(root, key, -1);
        pool.replace(root, next_root);
        pool.discard_unreferenced();
        return true;
    }

    bool erase_inplace(const T& key) { return erase_one_inplace(key); }

    PersistentOrderedMultiset erase_all(const T& key) const {
        const int old_count = count(key);
        if (old_count == 0) return *this;
        auto [l, r] = split_nodes(root, key);
        auto [discarded, rest] = pop_min(r);
        assert(equal(pool[discarded].key, key));
        return make_version(merge_nodes(l, rest));
    }

    bool erase_all_inplace(const T& key) {
        if (!contains(key)) return false;
        *this = erase_all(key);
        return true;
    }

    bool contains(const T& key) const { return count(key) > 0; }
    int count(const T& key) const { return count_impl(root, key); }

    const T* find_by_order(int k) const {
        assert(0 <= k && k < size());
        return kth_impl(root, k);
    }

    T kth(int k) const { return *find_by_order(k); }
    int order_of_key(const T& key) const { return order_of_key_impl(root, key, false); }
    int count_less(const T& key) const { return order_of_key(key); }
    int count_less_equal(const T& key) const { return order_of_key_impl(root, key, true); }
    int count_greater(const T& key) const { return size() - count_less_equal(key); }
    int count_greater_equal(const T& key) const { return size() - count_less(key); }
    const T* lower_bound(const T& key) const { return lower_bound_impl(root, key, false); }
    const T* upper_bound(const T& key) const { return lower_bound_impl(root, key, true); }
    const T* min_ge(const T& key) const { return lower_bound(key); }
    const T* min_gt(const T& key) const { return upper_bound(key); }
    const T* max_le(const T& key) const { return max_less_impl(root, key, false); }
    const T* max_lt(const T& key) const { return max_less_impl(root, key, true); }
    const T* min() const { return empty() ? nullptr : &pool[pool[root].min_leaf].key; }
    const T* max() const { return empty() ? nullptr : &pool[pool[root].max_leaf].key; }

    std::pair<PersistentOrderedMultiset, PersistentOrderedMultiset> split(const T& key) const {
        auto [l, r] = split_nodes(root, key);
        PersistentOrderedMultiset left(l, comp);
        PersistentOrderedMultiset right(r, comp);
        pool.discard_unreferenced();
        return {std::move(left), std::move(right)};
    }

    PersistentOrderedMultiset merge(const PersistentOrderedMultiset& other) const {
        assert(empty() || other.empty() || comp(*max(), *other.min()));
        return make_version(merge_nodes(root, other.root));
    }

    std::vector<T> to_vector() const {
        std::vector<T> result;
        result.reserve(size());
        dump_impl(root, result);
        return result;
    }
};

}  // namespace ds
}  // namespace m1une


#line 11 "ds/bst/persistent_ordered_set.hpp"

namespace m1une {
namespace ds {

template <typename T, typename Compare = std::less<T>>
struct PersistentOrderedSet {
   private:
    using Multiset = PersistentOrderedMultiset<T, Compare>;

    Multiset data;

    explicit PersistentOrderedSet(Multiset multiset) : data(std::move(multiset)) {}

   public:
    explicit PersistentOrderedSet(Compare compare) : data(std::move(compare)) {}

    PersistentOrderedSet() : PersistentOrderedSet(Compare()) {}

    PersistentOrderedSet(std::initializer_list<T> init, Compare compare = Compare())
        : PersistentOrderedSet(std::move(compare)) {
        for (const T& x : init) *this = insert(x);
    }

    template <typename Iterator>
    PersistentOrderedSet(Iterator first, Iterator last, Compare compare = Compare())
        : PersistentOrderedSet(std::move(compare)) {
        while (first != last) {
            *this = insert(*first);
            ++first;
        }
    }

    int size() const {
        return data.size();
    }

    int unique_size() const {
        return data.size();
    }

    bool empty() const {
        return data.empty();
    }

    void release() {
        data.release();
    }

    std::size_t node_count() const {
        return data.node_count();
    }

    PersistentOrderedSet clear() const {
        return PersistentOrderedSet(data.clear());
    }

    PersistentOrderedSet insert(T key) const {
        return PersistentOrderedSet(data.insert_unique(std::move(key)));
    }

    PersistentOrderedSet erase(const T& key) const {
        return PersistentOrderedSet(data.erase(key));
    }

    bool contains(const T& key) const {
        return data.contains(key);
    }

    int count(const T& key) const {
        return contains(key) ? 1 : 0;
    }

    const T* find_by_order(int k) const {
        return data.find_by_order(k);
    }

    T kth(int k) const {
        return data.kth(k);
    }

    int order_of_key(const T& key) const {
        return data.order_of_key(key);
    }

    int count_less(const T& key) const {
        return data.count_less(key);
    }

    int count_less_equal(const T& key) const {
        return data.count_less_equal(key);
    }

    int count_greater(const T& key) const {
        return data.count_greater(key);
    }

    int count_greater_equal(const T& key) const {
        return data.count_greater_equal(key);
    }

    const T* lower_bound(const T& key) const {
        return data.lower_bound(key);
    }

    const T* upper_bound(const T& key) const {
        return data.upper_bound(key);
    }

    const T* min_ge(const T& key) const {
        return data.min_ge(key);
    }

    const T* min_gt(const T& key) const {
        return data.min_gt(key);
    }

    const T* max_le(const T& key) const {
        return data.max_le(key);
    }

    const T* max_lt(const T& key) const {
        return data.max_lt(key);
    }

    const T* min() const {
        return data.min();
    }

    const T* max() const {
        return data.max();
    }

    std::pair<PersistentOrderedSet, PersistentOrderedSet> split(const T& key) const {
        auto [l, r] = data.split(key);
        return {PersistentOrderedSet(std::move(l)), PersistentOrderedSet(std::move(r))};
    }

    PersistentOrderedSet merge(const PersistentOrderedSet& other) const {
        return PersistentOrderedSet(data.merge(other.data));
    }

    std::vector<T> to_vector() const {
        return data.to_vector();
    }
};

}  // namespace ds
}  // namespace m1une


#line 4 "verify/ds/bst/persistent_ordered_set.test.cpp"

#line 1 "utilities/fast_io.hpp"



#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#line 9 "utilities/fast_io.hpp"
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <string>
#include <sys/stat.h>
#include <type_traits>
#line 18 "utilities/fast_io.hpp"
#include <unistd.h>
#line 20 "utilities/fast_io.hpp"

namespace m1une {
namespace utilities {

struct FastOutput;

namespace internal {

// Shared with the convenience helpers in template.hpp.
inline FastOutput* standard_output_instance = nullptr;

// Detect std::begin(x), std::end(x).
template <class T, class = void>
struct is_range : std::false_type {};

template <class T>
struct is_range<T, std::void_t<
    decltype(std::begin(std::declval<T&>())),
    decltype(std::end(std::declval<T&>()))
>> : std::true_type {};

template <class T>
inline constexpr bool is_range_v = is_range<T>::value;

template <class T>
using range_reference_t = decltype(*std::begin(std::declval<T&>()));

template <class T>
using range_value_t = std::remove_cv_t<std::remove_reference_t<range_reference_t<T>>>;

template <class T, class = void>
struct range_stored_value {
    using type = range_value_t<T>;
};

template <class T>
struct range_stored_value<T, std::void_t<typename std::remove_cv_t<std::remove_reference_t<T>>::value_type>> {
    using type = typename std::remove_cv_t<std::remove_reference_t<T>>::value_type;
};

template <class T>
using range_stored_value_t = typename range_stored_value<T>::type;

// Treat strings and C strings as scalar output objects, not as ranges.
template <class T>
struct is_char_array : std::false_type {};

template <class T, std::size_t N>
struct is_char_array<T[N]>
    : std::bool_constant<std::is_same_v<std::remove_cv_t<T>, char>> {};

template <class T>
struct is_string_like
    : std::bool_constant<
          std::is_same_v<std::decay_t<T>, std::string>
          || std::is_same_v<std::decay_t<T>, const char*>
          || std::is_same_v<std::decay_t<T>, char*>
          || is_char_array<std::remove_reference_t<T>>::value
      > {};

template <class T>
inline constexpr bool is_string_like_v = is_string_like<T>::value;

// ModInt-like type: x.val() is printable, and x can be assigned from long long.
template <class T, class = void>
struct has_val_method : std::false_type {};

template <class T>
struct has_val_method<T, std::void_t<decltype(std::declval<const T&>().val())>>
    : std::true_type {};

template <class T>
inline constexpr bool has_val_method_v = has_val_method<T>::value;

template <class T, class = void>
struct has_static_mod_raw : std::false_type {};

template <class T>
struct has_static_mod_raw<
    T, std::void_t<decltype(T::mod()), decltype(T::raw(std::declval<uint32_t>()))>>
    : std::true_type {};

template <class T>
inline constexpr bool has_static_mod_raw_v = has_static_mod_raw<T>::value;

// libstdc++ before GCC 16 does not classify __int128 as an integral type in
// strict ISO modes such as -std=c++23. Keep the fast-I/O interface independent
// of that implementation detail.
template <class T>
inline constexpr bool is_integral_v =
    std::is_integral_v<T>
    || std::is_same_v<std::remove_cv_t<T>, __int128_t>
    || std::is_same_v<std::remove_cv_t<T>, __uint128_t>;

template <class T>
inline constexpr bool is_signed_v =
    std::is_signed_v<T>
    || std::is_same_v<std::remove_cv_t<T>, __int128_t>;

template <class T>
struct make_unsigned {
    using type = std::make_unsigned_t<T>;
};

template <>
struct make_unsigned<__int128_t> {
    using type = __uint128_t;
};

template <>
struct make_unsigned<__uint128_t> {
    using type = __uint128_t;
};

template <class T>
using make_unsigned_t = typename make_unsigned<std::remove_cv_t<T>>::type;

}  // namespace internal

struct FastInput {
    static constexpr int buffer_size = 1 << 20;

   private:
    std::FILE* _stream;
    char _buffer[buffer_size];
    int _position;
    int _length;
    int _file_descriptor;
    bool _streaming;

    bool refill() {
        _position = 0;
        if (_streaming) {
            ssize_t length;
            do {
                length = ::read(_file_descriptor, _buffer, buffer_size);
            } while (length < 0 && errno == EINTR);
            if (length <= 0) {
                _length = 0;
                return false;
            }
            _length = int(length);
        } else {
            _length = int(std::fread(_buffer, 1, buffer_size, _stream));
        }
        return _length != 0;
    }

    template <class T>
    bool read_integer_from_stream(T& value) {
        if (!skip_spaces()) return false;
        int c = read_char_raw();

        bool negative = false;
        if (c == '-') {
            negative = true;
            c = read_char_raw();
        }

        if constexpr (internal::is_signed_v<T>) {
            T result = 0;
            while ('0' <= c && c <= '9') {
                result = negative ? result * 10 - (c - '0')
                                  : result * 10 + (c - '0');
                c = read_char_raw();
            }
            value = result;
        } else {
            T result = 0;
            while ('0' <= c && c <= '9') {
                result = result * 10 + T(c - '0');
                c = read_char_raw();
            }
            value = negative ? T(0) - result : result;
        }
        return true;
    }

    bool prepare_number() {
        if (_length - _position >= 64) return true;
        const int remaining = _length - _position;
        if (remaining > 0) std::memmove(_buffer, _buffer + _position, remaining);
        const int added = int(std::fread(_buffer + remaining, 1, buffer_size - remaining, _stream));
        _position = 0;
        _length = remaining + added;
        if (_length < buffer_size) _buffer[_length] = '\0';
        return _length != 0;
    }

   public:
    explicit FastInput(std::FILE* stream = stdin)
        : _stream(stream),
          _position(0),
          _length(0),
          _file_descriptor(::fileno(stream)),
          _streaming([&] {
              struct stat status;
              return _file_descriptor >= 0
                     && ::fstat(_file_descriptor, &status) == 0
                     && !S_ISREG(status.st_mode);
          }()) {}

    FastInput(const FastInput&) = delete;
    FastInput& operator=(const FastInput&) = delete;

    int read_char_raw() {
        if (_position == _length && !refill()) return EOF;
        return _buffer[_position++];
    }

    bool skip_spaces() {
        int c = read_char_raw();
        while (c != EOF && c <= ' ') c = read_char_raw();
        if (c == EOF) return false;
        --_position;
        return true;
    }

    bool read(char& value) {
        if (!skip_spaces()) return false;
        value = char(read_char_raw());
        return true;
    }

    bool read(std::string& value) {
        if (!skip_spaces()) return false;
        value.clear();
        while (true) {
            const int begin = _position;
            while (_position < _length &&
                   static_cast<unsigned char>(_buffer[_position]) > ' ') {
                ++_position;
            }
            value.append(_buffer + begin, _position - begin);
            if (_position < _length) {
                ++_position;
                return true;
            }
            if (!refill()) return true;
        }
    }

    bool read(bool& value) {
        int x;
        if (!read(x)) return false;
        value = x != 0;
        return true;
    }

    template <class T>
    std::enable_if_t<
        internal::is_integral_v<T>
            && !std::is_same_v<std::remove_cv_t<T>, bool>
            && !std::is_same_v<std::remove_cv_t<T>, char>,
        bool
    >
    read(T& value) {
        if (_streaming) return read_integer_from_stream(value);
        if (!prepare_number()) return false;
        int c = static_cast<unsigned char>(_buffer[_position++]);
        while (c <= ' ') c = static_cast<unsigned char>(_buffer[_position++]);

        bool negative = false;
        if (c == '-') {
            negative = true;
            c = static_cast<unsigned char>(_buffer[_position++]);
        }

        if constexpr (internal::is_signed_v<T>) {
            T result = 0;
            while ('0' <= c && c <= '9') {
                const int first = c - '0';
                const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
                if (0 <= second && second <= 9) {
                    result = negative ? result * 100 - (first * 10 + second)
                                      : result * 100 + (first * 10 + second);
                    ++_position;
                } else {
                    result = negative ? result * 10 - first : result * 10 + first;
                }
                c = static_cast<unsigned char>(_buffer[_position++]);
            }
            value = result;
        } else {
            T result = 0;
            while ('0' <= c && c <= '9') {
                const unsigned first = unsigned(c - '0');
                const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
                if (0 <= second && second <= 9) {
                    result = result * 100 + T(first * 10 + unsigned(second));
                    ++_position;
                } else {
                    result = result * 10 + T(first);
                }
                c = static_cast<unsigned char>(_buffer[_position++]);
            }
            value = negative ? T(0) - result : result;
        }
        if (_position > _length) _position = _length;
        return true;
    }

    template <class T>
    std::enable_if_t<std::is_floating_point_v<T>, bool>
    read(T& value) {
        if (!skip_spaces()) return false;
        int c = read_char_raw();
        bool negative = false;
        if (c == '-' || c == '+') {
            negative = c == '-';
            c = read_char_raw();
        }

        long double result = 0;
        while ('0' <= c && c <= '9') {
            result = result * 10 + (c - '0');
            c = read_char_raw();
        }
        if (c == '.') {
            long double place = 0.1L;
            c = read_char_raw();
            while ('0' <= c && c <= '9') {
                result += (c - '0') * place;
                place *= 0.1L;
                c = read_char_raw();
            }
        }
        if (c == 'e' || c == 'E') {
            c = read_char_raw();
            bool exponent_negative = false;
            if (c == '-' || c == '+') {
                exponent_negative = c == '-';
                c = read_char_raw();
            }
            int exponent = 0;
            while ('0' <= c && c <= '9') {
                exponent = exponent * 10 + (c - '0');
                c = read_char_raw();
            }
            long double scale = 1;
            long double power = 10;
            while (exponent > 0) {
                if (exponent & 1) scale *= power;
                power *= power;
                exponent >>= 1;
            }
            result = exponent_negative ? result / scale : result * scale;
        }
        value = static_cast<T>(negative ? -result : result);
        return true;
    }

    template <class T>
    std::enable_if_t<
        internal::has_val_method_v<T>
            && !internal::is_integral_v<T>
            && !internal::is_range_v<T>,
        bool
    >
    read(T& value) {
        long long x;
        if (!read(x)) return false;
        if constexpr (internal::has_static_mod_raw_v<T>) {
            if (x >= 0 && uint64_t(x) < uint64_t(T::mod())) {
                value = T::raw(uint32_t(x));
            } else {
                value = T(x);
            }
        } else {
            value = T(x);
        }
        return true;
    }

    template <class First, class Second>
    bool read(std::pair<First, Second>& value) {
        if (!read(value.first)) return false;
        return read(value.second);
    }

    template <class Range>
    std::enable_if_t<
        internal::is_range_v<Range>
            && !internal::is_string_like_v<Range>,
        bool
    >
    read(Range& range) {
        using StoredValue = internal::range_stored_value_t<Range>;
        constexpr bool nested = internal::is_range_v<StoredValue>
                                && !internal::is_string_like_v<StoredValue>;

        for (auto&& value : range) {
            if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
                bool x;
                if (!read(x)) return false;
                value = x;
            } else {
                if (!read(value)) return false;
            }
        }
        return true;
    }

    template <class First, class Second, class... Rest>
    bool read(First& first, Second& second, Rest&... rest) {
        if (!read(first)) return false;
        return read(second, rest...);
    }

    template <class T>
    FastInput& operator>>(T& value) {
        if (!read(value)) std::abort();
        return *this;
    }
};

struct FastOutput {
    static constexpr int buffer_size = 1 << 20;

   private:
    inline static const auto digit_quads = [] {
        std::array<char, 40000> result{};
        for (int i = 0; i < 10000; i++) {
            int value = i;
            for (int j = 3; j >= 0; j--) {
                result[4 * i + j] = char('0' + value % 10);
                value /= 10;
            }
        }
        return result;
    }();

    std::FILE* _stream;
    char _buffer[buffer_size];
    int _position;
    int _precision;
    std::chars_format _float_format;
    char _range_separator;
    std::string* _capture = nullptr;

    template <class T>
    std::string format_cell(const T& value) {
        std::string result;
        struct CaptureGuard {
            std::string*& target;
            std::string* previous;
            ~CaptureGuard() { target = previous; }
        } guard{_capture, _capture};
        _capture = &result;
        write(value);
        return result;
    }

    template <class Matrix>
    void write_aligned_matrix(const Matrix& matrix) {
        std::vector<std::vector<std::string>> rows;
        std::vector<std::size_t> widths;
        for (const auto& row : matrix) {
            auto& cells = rows.emplace_back();
            std::size_t column = 0;
            for (const auto& value : row) {
                cells.push_back(format_cell(value));
                if (column == widths.size()) widths.push_back(0);
                widths[column] = std::max(widths[column], cells.back().size());
                ++column;
            }
        }
        bool first = true;
        for (const auto& row : rows) {
            if (!first) write_char('\n');
            first = false;
            for (std::size_t column = 0; column < row.size(); ++column) {
                if (column != 0) write_char(_range_separator);
                for (std::size_t padding = row[column].size();
                     padding < widths[column]; ++padding) {
                    write_char(' ');
                }
                write(row[column]);
            }
        }
    }

   public:
    explicit FastOutput(std::FILE* stream = stdout)
        : _stream(stream),
          _position(0),
          _precision(6),
          _float_format(std::chars_format::general),
          _range_separator(' ') {
        if (_stream == stdout
            && internal::standard_output_instance == nullptr) {
            internal::standard_output_instance = this;
        }
    }

    FastOutput(const FastOutput&) = delete;
    FastOutput& operator=(const FastOutput&) = delete;

    ~FastOutput() {
        flush();
        if (internal::standard_output_instance == this) {
            internal::standard_output_instance = nullptr;
        }
    }

    void flush() {
        if (_position != 0) {
            std::fwrite(_buffer, 1, _position, _stream);
            _position = 0;
        }
        std::fflush(_stream);
    }

    void write_char(char c) {
        if (_capture != nullptr) {
            _capture->push_back(c);
            return;
        }
        if (_position == buffer_size) flush();
        _buffer[_position++] = c;
    }

    void write(const char* s) {
        while (*s != '\0') write_char(*s++);
    }

    void write(const std::string& s) {
        if (_capture != nullptr) {
            _capture->append(s);
            return;
        }
        std::size_t position = 0;
        while (position < s.size()) {
            if (_position == buffer_size) flush();
            const std::size_t copied =
                std::min<std::size_t>(buffer_size - _position, s.size() - position);
            std::memcpy(_buffer + _position, s.data() + position, copied);
            _position += int(copied);
            position += copied;
        }
    }

    void write(char c) {
        write_char(c);
    }

    void write(bool value) {
        write_char(value ? '1' : '0');
    }

    template <class T>
    std::enable_if_t<std::is_floating_point_v<T>>
    write(T value) {
        char digits[128];
        auto [end, error] = std::to_chars(
            digits,
            digits + sizeof(digits),
            value,
            _float_format,
            _precision
        );
        if (error != std::errc()) std::abort();
        for (const char* pointer = digits; pointer != end; pointer++) {
            write_char(*pointer);
        }
    }

    template <class T>
    std::enable_if_t<
        internal::is_integral_v<T>
            && !std::is_same_v<std::remove_cv_t<T>, bool>
            && !std::is_same_v<std::remove_cv_t<T>, char>
    >
    write(T value) {
        using Raw = std::remove_cv_t<T>;
        using Unsigned = internal::make_unsigned_t<Raw>;

        Unsigned magnitude;
        if constexpr (internal::is_signed_v<Raw>) {
            if (value < 0) {
                write_char('-');
                magnitude = Unsigned(0) - Unsigned(value);
            } else {
                magnitude = Unsigned(value);
            }
        } else {
            magnitude = value;
        }

        if (magnitude == 0) {
            write_char('0');
            return;
        }

        unsigned chunks[16];
        int count = 0;
        while (magnitude >= 10000) {
            const Unsigned quotient = magnitude / 10000;
            chunks[count++] = unsigned(magnitude - quotient * 10000);
            magnitude = quotient;
        }
        if (_capture == nullptr && _position > buffer_size - 64) flush();
        char captured[64];
        char* const begin = _capture != nullptr ? captured : _buffer + _position;
        char* destination = begin;
        const unsigned leading = unsigned(magnitude);
        const char* first = digit_quads.data() + 4 * leading;
        int skip = leading < 10 ? 3 : leading < 100 ? 2 : leading < 1000 ? 1 : 0;
        for (; skip < 4; skip++) *destination++ = first[skip];
        while (count--) {
            const char* digits = digit_quads.data() + 4 * chunks[count];
            std::memcpy(destination, digits, 4);
            destination += 4;
        }
        if (_capture != nullptr) {
            _capture->append(begin, destination - begin);
        } else {
            _position += int(destination - begin);
        }
    }

    template <class T>
    std::enable_if_t<
        internal::has_val_method_v<T>
            && !internal::is_integral_v<T>
            && !internal::is_range_v<T>
    >
    write(const T& value) {
        write(value.val());
    }

    template <class First, class Second>
    void write(const std::pair<First, Second>& value) {
        write(value.first);
        write_char(' ');
        write(value.second);
    }

    template <class Range>
    std::enable_if_t<
        internal::is_range_v<Range>
            && !internal::is_string_like_v<Range>
    >
    write(const Range& range) {
        using StoredValue = internal::range_stored_value_t<const Range>;
        constexpr bool nested = internal::is_range_v<StoredValue>
                                && !internal::is_string_like_v<StoredValue>;

        bool first = true;
        for (const auto& value : range) {
            if (!first) write_char(nested ? '\n' : _range_separator);
            first = false;
            if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
                write(static_cast<bool>(value));
            } else {
                write(value);
            }
        }
    }

    template <class First, class... Rest>
    void print(const First& first, const Rest&... rest) {
        write(first);
        ((write_char(' '), write(rest)), ...);
    }

    void println() {
        write_char('\n');
    }

    void set_precision(int precision) {
        _precision = precision;
    }

    void set_fixed(int precision = 6) {
        _float_format = std::chars_format::fixed;
        _precision = precision;
    }

    void set_general(int precision = 6) {
        _float_format = std::chars_format::general;
        _precision = precision;
    }

    void set_range_separator(char separator) {
        _range_separator = separator;
    }

    template <class Matrix>
    void write_aligned(const Matrix& matrix) {
        using Row = internal::range_stored_value_t<const Matrix>;
        using Cell = internal::range_stored_value_t<const Row>;
        static_assert(internal::is_range_v<Row> && !internal::is_string_like_v<Row>,
                      "write_aligned requires a two-dimensional range");
        static_assert(!internal::is_range_v<Cell> || internal::is_string_like_v<Cell>,
                      "write_aligned requires scalar cells");
        write_aligned_matrix(matrix);
    }

    template <class Matrix>
    void println_aligned(const Matrix& matrix) {
        write_aligned(matrix);
        write_char('\n');
    }

    template <class... Args>
    void println(const Args&... args) {
        print(args...);
        write_char('\n');
    }

    template <class T>
    FastOutput& operator<<(const T& value) {
        write(value);
        return *this;
    }
};

}  // namespace utilities
}  // namespace m1une


#line 7 "verify/ds/bst/persistent_ordered_set.test.cpp"

int main() {
    m1une::utilities::FastInput fast_input;
    m1une::utilities::FastOutput fast_output;

    m1une::ds::PersistentOrderedSet<int> pointer_test = {1, 3, 5};
    const int* stable_pointer = pointer_test.lower_bound(3);
    auto pointer_test_next = pointer_test;
    for (int x = 10; x < 1000; x++) pointer_test_next = pointer_test_next.insert(x);
    assert(stable_pointer && *stable_pointer == 3);
    auto [small, large] = pointer_test_next.split(500);
    auto joined = small.merge(large);
    assert(pointer_test_next.size() == joined.size());
    assert(pointer_test_next.to_vector() == joined.to_vector());

    int N, Q;
    fast_input >> N >> Q;

    m1une::ds::PersistentOrderedSet<int> st;
    for (int i = 0; i < N; i++) {
        int a;
        fast_input >> a;
        st = st.insert(a);
    }

    while (Q--) {
        int type, x;
        fast_input >> type >> x;

        if (type == 0) {
            st = st.insert(x);
        } else if (type == 1) {
            st = st.erase(x);
        } else if (type == 2) {
            if (st.size() < x) {
                fast_output << -1 << '\n';
            } else {
                fast_output << st.kth(x - 1) << '\n';
            }
        } else if (type == 3) {
            fast_output << st.count_less_equal(x) << '\n';
        } else if (type == 4) {
            const int* ans = st.max_le(x);
            fast_output << (ans ? *ans : -1) << '\n';
        } else {
            const int* ans = st.min_ge(x);
            fast_output << (ans ? *ans : -1) << '\n';
        }
    }
}
Back to top page