m1une's library

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

View on GitHub

:heavy_check_mark: verify/ds/range_query/range_majority.test.cpp

Depends on

Code

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

#include "../../../ds/range_query/range_majority.hpp"

#include <cassert>
#include <cstdint>
#include "../../../utilities/fast_io.hpp"
#include <map>
#include <optional>
#include <utility>
#include <vector>

namespace {

std::optional<int> brute(
    const std::vector<int>& values,
    int left,
    int right
) {
    std::map<int, int> frequency;
    for (int index = left; index < right; index++) {
        int count = ++frequency[values[index]];
        if (count * 2 > right - left) return values[index];
    }
    return std::nullopt;
}

void test_randomized() {
    m1une::ds::RangeMajority<int> empty;
    assert(empty.empty());
    assert(empty.size() == 0);

    std::uint64_t state = 1414213562ULL;
    auto random = [&]() {
        state ^= state << 7;
        state ^= state >> 9;
        return state;
    };

    for (int trial = 0; trial < 1000; trial++) {
        int n = int(random() % 80) + 1;
        std::vector<int> values(n);
        for (int& value : values) value = int(random() % 15) - 7;

        m1une::ds::RangeMajority<int> structure(values);
        assert(structure.size() == n);
        assert(!structure.empty());
        for (int left = 0; left < n; left++) {
            for (int right = left + 1; right <= n; right++) {
                std::optional<int> expected = brute(values, left, right);
                assert(structure.query(left, right) == expected);
                assert(structure.majority(left, right) == expected);
            }
        }
    }

    for (int trial = 0; trial < 500; trial++) {
        int n = int(random() % 80) + 1;
        std::vector<int> values(n);
        for (int& value : values) value = int(random() % 15) - 7;

        m1une::ds::RangeMajority<int> structure(values);
        for (int operation = 0; operation < 500; operation++) {
            if (random() % 2 == 0) {
                int index = int(random() % n);
                int value = int(random() % 31) - 15;
                structure.set(index, value);
                values[index] = value;
            } else {
                int left = int(random() % n);
                int right = int(random() % n);
                if (left > right) std::swap(left, right);
                ++right;
                std::optional<int> expected = brute(values, left, right);
                assert(structure.query(left, right) == expected);
                assert(structure.majority(left, right) == expected);
            }
        }
    }
}

}  // namespace

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

    test_randomized();

    int size, query_count;
    fast_input >> size >> query_count;
    std::vector<int> values(size);
    for (int& value : values) fast_input >> value;

    m1une::ds::RangeMajority<int> structure(values);
    while (query_count--) {
        int type, first, second;
        fast_input >> type >> first >> second;
        if (type == 0) {
            structure.set(first, second);
        } else {
            std::optional<int> result = structure.majority(first, second);
            fast_output << (result.has_value() ? *result : -1) << '\n';
        }
    }
}
#line 1 "verify/ds/range_query/range_majority.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/majority_voting"

#line 1 "ds/range_query/range_majority.hpp"



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



#include <cassert>
#include <functional>
#include <initializer_list>
#include <memory>
#include <utility>
#include <vector>

namespace m1une {
namespace ds {

template <typename T, typename Compare = std::less<T>>
struct OrderedSet {
   private:
    struct Node {
        T key;
        int size;
        Node* l;
        Node* r;

        explicit Node(T value)
            : key(std::move(value)), size(1), l(nullptr), r(nullptr) {}
    };

    static constexpr int pool_block_size = 1 << 15;

    struct Pool {
        std::vector<std::vector<Node>> blocks;
        std::vector<Node*> free_nodes;

        template <class... Args>
        Node* emplace(Args&&... args) {
            if (!free_nodes.empty()) {
                Node* result = free_nodes.back();
                free_nodes.pop_back();
                std::destroy_at(result);
                std::construct_at(result, std::forward<Args>(args)...);
                return result;
            }
            if (blocks.empty() || int(blocks.back().size()) == pool_block_size) {
                blocks.emplace_back();
                blocks.back().reserve(pool_block_size);
            }
            blocks.back().emplace_back(std::forward<Args>(args)...);
            return &blocks.back().back();
        }

        void recycle(Node* node) {
            free_nodes.push_back(node);
        }
    };

    inline static Pool pool;

    Node* root;
    Compare comp;

    static int subtree_size(const Node* t) {
        return t == nullptr ? 0 : t->size;
    }

    Node* new_node(T key) {
        return pool.emplace(std::move(key));
    }

    static void update(Node* t) {
        t->size = 1 + subtree_size(t->l) + subtree_size(t->r);
    }

    static Node* rotate_right(Node* t) {
        Node* s = t->l;
        t->l = s->r;
        s->r = t;
        update(t);
        update(s);
        return s;
    }

    static Node* rotate_left(Node* t) {
        Node* s = t->r;
        t->r = s->l;
        s->l = t;
        update(t);
        update(s);
        return s;
    }

    static Node* balance(Node* t) {
        if (t == nullptr) return nullptr;
        const int left_size = subtree_size(t->l);
        const int right_size = subtree_size(t->r);
        if (left_size + right_size > 1 && left_size > 3LL * right_size) {
            if (subtree_size(t->l->r) >= 2LL * subtree_size(t->l->l)) {
                t->l = rotate_left(t->l);
            }
            return rotate_right(t);
        }
        if (left_size + right_size > 1 && right_size > 3LL * left_size) {
            if (subtree_size(t->r->l) >= 2LL * subtree_size(t->r->r)) {
                t->r = rotate_right(t->r);
            }
            return rotate_left(t);
        }
        update(t);
        return t;
    }

    static Node* join_with_root(Node* l, Node* middle, Node* r) {
        const int left_size = subtree_size(l);
        const int right_size = subtree_size(r);
        if (left_size > 3LL * (right_size + 1)) {
            l->r = join_with_root(l->r, middle, r);
            return balance(l);
        }
        if (right_size > 3LL * (left_size + 1)) {
            r->l = join_with_root(l, middle, r->l);
            return balance(r);
        }
        middle->l = l;
        middle->r = r;
        return balance(middle);
    }

    static Node* detach_max(Node* t, Node*& maximum) {
        if (t->r == nullptr) {
            maximum = t;
            return t->l;
        }
        t->r = detach_max(t->r, maximum);
        return balance(t);
    }

    static Node* merge_nodes(Node* l, Node* r) {
        if (l == nullptr || r == nullptr) return l == nullptr ? r : l;
        Node* middle;
        l = detach_max(l, middle);
        return join_with_root(l, middle, r);
    }

    std::pair<Node*, Node*> split_nodes(Node* t, const T& key) {
        if (t == nullptr) return {nullptr, nullptr};
        Node* left = t->l;
        Node* right = t->r;
        t->l = nullptr;
        t->r = nullptr;
        if (comp(t->key, key)) {
            auto [l, r] = split_nodes(right, key);
            return {join_with_root(left, t, l), r};
        }
        auto [l, r] = split_nodes(left, key);
        return {l, join_with_root(r, t, right)};
    }

    Node* insert_impl(Node* t, T& key, bool& inserted) {
        if (t == nullptr) {
            inserted = true;
            return new_node(std::move(key));
        }
        if (comp(key, t->key)) {
            t->l = insert_impl(t->l, key, inserted);
        } else if (comp(t->key, key)) {
            t->r = insert_impl(t->r, key, inserted);
        } else {
            return t;
        }
        if (!inserted) return t;
        return balance(t);
    }

    Node* erase_impl(Node* t, const T& key, bool& erased) {
        if (t == nullptr) return nullptr;
        if (comp(key, t->key)) {
            t->l = erase_impl(t->l, key, erased);
        } else if (comp(t->key, key)) {
            t->r = erase_impl(t->r, key, erased);
        } else {
            erased = true;
            Node* l = t->l;
            Node* r = t->r;
            pool.recycle(t);
            return merge_nodes(l, r);
        }
        if (!erased) return t;
        return balance(t);
    }

    static const T* kth_impl(const Node* t, int k) {
        while (t != nullptr) {
            const int left_size = subtree_size(t->l);
            if (k < left_size) {
                t = t->l;
            } else if (k == left_size) {
                return &t->key;
            } else {
                k -= left_size + 1;
                t = t->r;
            }
        }
        return nullptr;
    }

    int order_of_key_impl(const Node* t, const T& key, bool upper) const {
        int result = 0;
        while (t != nullptr) {
            const bool take = upper ? !comp(key, t->key) : comp(t->key, key);
            if (take) {
                result += subtree_size(t->l) + 1;
                t = t->r;
            } else {
                t = t->l;
            }
        }
        return result;
    }

    const T* lower_bound_impl(const Node* t, const T& key, bool strict) const {
        const T* result = nullptr;
        while (t != nullptr) {
            const bool candidate = strict ? comp(key, t->key) : !comp(t->key, key);
            if (candidate) {
                result = &t->key;
                t = t->l;
            } else {
                t = t->r;
            }
        }
        return result;
    }

    const T* max_less_impl(const Node* t, const T& key, bool strict) const {
        const T* result = nullptr;
        while (t != nullptr) {
            const bool candidate = strict ? comp(t->key, key) : !comp(key, t->key);
            if (candidate) {
                result = &t->key;
                t = t->r;
            } else {
                t = t->l;
            }
        }
        return result;
    }

    bool contains_impl(const Node* t, const T& key) const {
        while (t != nullptr) {
            if (comp(key, t->key)) {
                t = t->l;
            } else if (comp(t->key, key)) {
                t = t->r;
            } else {
                return true;
            }
        }
        return false;
    }

    static void dump_impl(const Node* t, std::vector<T>& result) {
        if (t == nullptr) return;
        dump_impl(t->l, result);
        result.push_back(t->key);
        dump_impl(t->r, result);
    }

    static void recycle_impl(Node* t) {
        if (t == nullptr) return;
        recycle_impl(t->l);
        recycle_impl(t->r);
        pool.recycle(t);
    }

    Node* clone_impl(const Node* t) {
        if (t == nullptr) return nullptr;
        Node* result = new_node(t->key);
        result->l = clone_impl(t->l);
        result->r = clone_impl(t->r);
        update(result);
        return result;
    }

    OrderedSet(Node* node, Compare compare) : root(node), comp(std::move(compare)) {}

   public:
    explicit OrderedSet(Compare compare)
        : root(nullptr), comp(std::move(compare)) {}

    OrderedSet() : OrderedSet(Compare()) {}

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

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

    OrderedSet(const OrderedSet& other)
        : root(nullptr), comp(other.comp) {
        root = clone_impl(other.root);
    }

    OrderedSet(OrderedSet&& other) noexcept
        : root(std::exchange(other.root, nullptr)), comp(std::move(other.comp)) {}

    ~OrderedSet() {
        recycle_impl(root);
    }

    OrderedSet& operator=(OrderedSet other) {
        swap(other);
        return *this;
    }

    void swap(OrderedSet& other) noexcept {
        using std::swap;
        swap(root, other.root);
        swap(comp, other.comp);
    }

    int size() const { return subtree_size(root); }
    int unique_size() const { return size(); }
    bool empty() const { return root == nullptr; }

    void clear() {
        recycle_impl(root);
        root = nullptr;
    }

    bool insert(T key) {
        bool inserted = false;
        root = insert_impl(root, key, inserted);
        return inserted;
    }

    bool erase(const T& key) {
        bool erased = false;
        root = erase_impl(root, key, erased);
        return erased;
    }

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

    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 : kth_impl(root, 0); }
    const T* max() const { return empty() ? nullptr : kth_impl(root, size() - 1); }

    std::pair<OrderedSet, OrderedSet> split(const T& key) && {
        auto [l, r] = split_nodes(root, key);
        root = nullptr;
        return {OrderedSet(l, comp), OrderedSet(r, std::move(comp))};
    }

    OrderedSet merge(OrderedSet other) && {
        assert(empty() || other.empty() || comp(*max(), *other.min()));
        root = merge_nodes(root, other.root);
        other.root = nullptr;
        return std::move(*this);
    }

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

}  // namespace ds
}  // namespace m1une


#line 5 "ds/range_query/range_majority.hpp"

#line 7 "ds/range_query/range_majority.hpp"
#include <map>
#include <optional>
#line 11 "ds/range_query/range_majority.hpp"

namespace m1une {
namespace ds {

// Strict-majority queries and point assignments in O(log N) time.
template <class T>
struct RangeMajority {
    using result_type = std::optional<T>;

   private:
    struct Vote {
        int candidate = -1;
        int balance = 0;
    };

    int _n;
    int _tree_size;
    std::vector<T> _values;
    std::map<T, int> _ranks;
    std::vector<int> _current;
    std::vector<OrderedSet<int>> _positions;
    std::vector<Vote> _tree;

    int register_value(T value) {
        int rank = int(_values.size());
        auto [iterator, inserted] = _ranks.emplace(std::move(value), rank);
        if (inserted) {
            _values.push_back(iterator->first);
            _positions.emplace_back();
        }
        return iterator->second;
    }

    static Vote combine(Vote first, Vote second) {
        if (first.balance == 0) return second;
        if (second.balance == 0) return first;
        if (first.candidate == second.candidate) {
            return Vote{first.candidate, first.balance + second.balance};
        }
        if (first.balance > second.balance) {
            return Vote{first.candidate, first.balance - second.balance};
        }
        if (second.balance > first.balance) {
            return Vote{second.candidate, second.balance - first.balance};
        }
        return Vote();
    }

    Vote range_vote(int left, int right) const {
        Vote left_vote;
        Vote right_vote;
        left += _tree_size;
        right += _tree_size;
        while (left < right) {
            if (left & 1) left_vote = combine(left_vote, _tree[left++]);
            if (right & 1) right_vote = combine(_tree[--right], right_vote);
            left >>= 1;
            right >>= 1;
        }
        return combine(left_vote, right_vote);
    }

   public:
    RangeMajority() : _n(0), _tree_size(1), _tree(2) {}

    explicit RangeMajority(const std::vector<T>& values)
        : _n(int(values.size())),
          _tree_size(1),
          _current(values.size()) {
        _values.reserve(values.size());
        _positions.reserve(values.size());
        while (_tree_size < _n) _tree_size <<= 1;
        _tree.assign(2 * _tree_size, Vote());
        for (int index = 0; index < _n; index++) {
            int rank = register_value(values[index]);
            _current[index] = rank;
            _positions[rank].insert(index);
            _tree[_tree_size + index] = Vote{rank, 1};
        }
        for (int node = _tree_size - 1; node > 0; node--) {
            _tree[node] = combine(_tree[node << 1], _tree[(node << 1) | 1]);
        }
    }

    int size() const {
        return _n;
    }

    bool empty() const {
        return _n == 0;
    }

    // Assigns value to one position. Previously unseen values are supported.
    void set(int index, T value) {
        assert(0 <= index && index < _n);
        int rank = register_value(std::move(value));
        int previous_rank = _current[index];
        if (rank == previous_rank) return;

        [[maybe_unused]] bool erased =
            _positions[previous_rank].erase(index);
        [[maybe_unused]] bool inserted = _positions[rank].insert(index);
        assert(erased && inserted);
        _current[index] = rank;

        int node = _tree_size + index;
        _tree[node] = Vote{rank, 1};
        while ((node >>= 1) != 0) {
            _tree[node] = combine(_tree[node << 1], _tree[(node << 1) | 1]);
        }
    }

    // Returns the unique value occurring more than half the time in
    // [left, right), or nullopt when no such value exists.
    result_type query(int left, int right) const {
        assert(0 <= left && left < right && right <= _n);
        Vote vote = range_vote(left, right);
        if (vote.balance == 0) return std::nullopt;

        const OrderedSet<int>& positions = _positions[vote.candidate];
        int frequency =
            positions.order_of_key(right) - positions.order_of_key(left);
        if (2LL * frequency <= right - left) return std::nullopt;
        return _values[vote.candidate];
    }

    result_type majority(int left, int right) const {
        return query(left, right);
    }
};

}  // namespace ds
}  // namespace m1une


#line 4 "verify/ds/range_query/range_majority.test.cpp"

#line 6 "verify/ds/range_query/range_majority.test.cpp"
#include <cstdint>
#line 1 "utilities/fast_io.hpp"



#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#line 12 "utilities/fast_io.hpp"
#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 12 "verify/ds/range_query/range_majority.test.cpp"

namespace {

std::optional<int> brute(
    const std::vector<int>& values,
    int left,
    int right
) {
    std::map<int, int> frequency;
    for (int index = left; index < right; index++) {
        int count = ++frequency[values[index]];
        if (count * 2 > right - left) return values[index];
    }
    return std::nullopt;
}

void test_randomized() {
    m1une::ds::RangeMajority<int> empty;
    assert(empty.empty());
    assert(empty.size() == 0);

    std::uint64_t state = 1414213562ULL;
    auto random = [&]() {
        state ^= state << 7;
        state ^= state >> 9;
        return state;
    };

    for (int trial = 0; trial < 1000; trial++) {
        int n = int(random() % 80) + 1;
        std::vector<int> values(n);
        for (int& value : values) value = int(random() % 15) - 7;

        m1une::ds::RangeMajority<int> structure(values);
        assert(structure.size() == n);
        assert(!structure.empty());
        for (int left = 0; left < n; left++) {
            for (int right = left + 1; right <= n; right++) {
                std::optional<int> expected = brute(values, left, right);
                assert(structure.query(left, right) == expected);
                assert(structure.majority(left, right) == expected);
            }
        }
    }

    for (int trial = 0; trial < 500; trial++) {
        int n = int(random() % 80) + 1;
        std::vector<int> values(n);
        for (int& value : values) value = int(random() % 15) - 7;

        m1une::ds::RangeMajority<int> structure(values);
        for (int operation = 0; operation < 500; operation++) {
            if (random() % 2 == 0) {
                int index = int(random() % n);
                int value = int(random() % 31) - 15;
                structure.set(index, value);
                values[index] = value;
            } else {
                int left = int(random() % n);
                int right = int(random() % n);
                if (left > right) std::swap(left, right);
                ++right;
                std::optional<int> expected = brute(values, left, right);
                assert(structure.query(left, right) == expected);
                assert(structure.majority(left, right) == expected);
            }
        }
    }
}

}  // namespace

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

    test_randomized();

    int size, query_count;
    fast_input >> size >> query_count;
    std::vector<int> values(size);
    for (int& value : values) fast_input >> value;

    m1une::ds::RangeMajority<int> structure(values);
    while (query_count--) {
        int type, first, second;
        fast_input >> type >> first >> second;
        if (type == 0) {
            structure.set(first, second);
        } else {
            std::optional<int> result = structure.majority(first, second);
            fast_output << (result.has_value() ? *result : -1) << '\n';
        }
    }
}
Back to top page